/*!
 * jQuery JavaScript Library v1.4.2
 * http://jquery.com/
 *
 * Copyright 2010, John Resig
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * Includes Sizzle.js
 * http://sizzlejs.com/
 * Copyright 2010, The Dojo Foundation
 * Released under the MIT, BSD, and GPL Licenses.
 *
 * Date: Sat Feb 13 22:33:48 2010 -0500
 */
(function(A,w){function ma(){if(!c.isReady){try{s.documentElement.doScroll("left")}catch(a){setTimeout(ma,1);return}c.ready()}}function Qa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function X(a,b,d,f,e,j){var i=a.length;if(typeof b==="object"){for(var o in b)X(a,o,b[o],f,e,d);return a}if(d!==w){f=!j&&f&&c.isFunction(d);for(o=0;o<i;o++)e(a[o],b,f?d.call(a[o],o,e(a[o],b)):d,j);return a}return i?
e(a[0],b):w}function J(){return(new Date).getTime()}function Y(){return false}function Z(){return true}function na(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function oa(a){var b,d=[],f=[],e=arguments,j,i,o,k,n,r;i=c.data(this,"events");if(!(a.liveFired===this||!i||!i.live||a.button&&a.type==="click")){a.liveFired=this;var u=i.live.slice(0);for(k=0;k<u.length;k++){i=u[k];i.origType.replace(O,"")===a.type?f.push(i.selector):u.splice(k--,1)}j=c(a.target).closest(f,a.currentTarget);n=0;for(r=
j.length;n<r;n++)for(k=0;k<u.length;k++){i=u[k];if(j[n].selector===i.selector){o=j[n].elem;f=null;if(i.preType==="mouseenter"||i.preType==="mouseleave")f=c(a.relatedTarget).closest(i.selector)[0];if(!f||f!==o)d.push({elem:o,handleObj:i})}}n=0;for(r=d.length;n<r;n++){j=d[n];a.currentTarget=j.elem;a.data=j.handleObj.data;a.handleObj=j.handleObj;if(j.handleObj.origHandler.apply(j.elem,e)===false){b=false;break}}return b}}function pa(a,b){return"live."+(a&&a!=="*"?a+".":"")+b.replace(/\./g,"`").replace(/ /g,
"&")}function qa(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function ra(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var f=c.data(a[d++]),e=c.data(this,f);if(f=f&&f.events){delete e.handle;e.events={};for(var j in f)for(var i in f[j])c.event.add(this,j,f[j][i],f[j][i].data)}}})}function sa(a,b,d){var f,e,j;b=b&&b[0]?b[0].ownerDocument||b[0]:s;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===s&&!ta.test(a[0])&&(c.support.checkClone||!ua.test(a[0]))){e=
true;if(j=c.fragments[a[0]])if(j!==1)f=j}if(!f){f=b.createDocumentFragment();c.clean(a,b,f,d)}if(e)c.fragments[a[0]]=j?f:1;return{fragment:f,cacheable:e}}function K(a,b){var d={};c.each(va.concat.apply([],va.slice(0,b)),function(){d[this]=a});return d}function wa(a){return"scrollTo"in a&&a.document?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var c=function(a,b){return new c.fn.init(a,b)},Ra=A.jQuery,Sa=A.$,s=A.document,T,Ta=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,Ua=/^.[^:#\[\.,]*$/,Va=/\S/,
Wa=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,Xa=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,P=navigator.userAgent,xa=false,Q=[],L,$=Object.prototype.toString,aa=Object.prototype.hasOwnProperty,ba=Array.prototype.push,R=Array.prototype.slice,ya=Array.prototype.indexOf;c.fn=c.prototype={init:function(a,b){var d,f;if(!a)return this;if(a.nodeType){this.context=this[0]=a;this.length=1;return this}if(a==="body"&&!b){this.context=s;this[0]=s.body;this.selector="body";this.length=1;return this}if(typeof a==="string")if((d=Ta.exec(a))&&
(d[1]||!b))if(d[1]){f=b?b.ownerDocument||b:s;if(a=Xa.exec(a))if(c.isPlainObject(b)){a=[s.createElement(a[1])];c.fn.attr.call(a,b,true)}else a=[f.createElement(a[1])];else{a=sa([d[1]],[f]);a=(a.cacheable?a.fragment.cloneNode(true):a.fragment).childNodes}return c.merge(this,a)}else{if(b=s.getElementById(d[2])){if(b.id!==d[2])return T.find(a);this.length=1;this[0]=b}this.context=s;this.selector=a;return this}else if(!b&&/^\w+$/.test(a)){this.selector=a;this.context=s;a=s.getElementsByTagName(a);return c.merge(this,
a)}else return!b||b.jquery?(b||T).find(a):c(b).find(a);else if(c.isFunction(a))return T.ready(a);if(a.selector!==w){this.selector=a.selector;this.context=a.context}return c.makeArray(a,this)},selector:"",jquery:"1.4.2",length:0,size:function(){return this.length},toArray:function(){return R.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this.slice(a)[0]:this[a]},pushStack:function(a,b,d){var f=c();c.isArray(a)?ba.apply(f,a):c.merge(f,a);f.prevObject=this;f.context=this.context;if(b===
"find")f.selector=this.selector+(this.selector?" ":"")+d;else if(b)f.selector=this.selector+"."+b+"("+d+")";return f},each:function(a,b){return c.each(this,a,b)},ready:function(a){c.bindReady();if(c.isReady)a.call(s,c);else Q&&Q.push(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(R.apply(this,arguments),"slice",R.call(arguments).join(","))},map:function(a){return this.pushStack(c.map(this,
function(b,d){return a.call(b,d,b)}))},end:function(){return this.prevObject||c(null)},push:ba,sort:[].sort,splice:[].splice};c.fn.init.prototype=c.fn;c.extend=c.fn.extend=function(){var a=arguments[0]||{},b=1,d=arguments.length,f=false,e,j,i,o;if(typeof a==="boolean"){f=a;a=arguments[1]||{};b=2}if(typeof a!=="object"&&!c.isFunction(a))a={};if(d===b){a=this;--b}for(;b<d;b++)if((e=arguments[b])!=null)for(j in e){i=a[j];o=e[j];if(a!==o)if(f&&o&&(c.isPlainObject(o)||c.isArray(o))){i=i&&(c.isPlainObject(i)||
c.isArray(i))?i:c.isArray(o)?[]:{};a[j]=c.extend(f,i,o)}else if(o!==w)a[j]=o}return a};c.extend({noConflict:function(a){A.$=Sa;if(a)A.jQuery=Ra;return c},isReady:false,ready:function(){if(!c.isReady){if(!s.body)return setTimeout(c.ready,13);c.isReady=true;if(Q){for(var a,b=0;a=Q[b++];)a.call(s,c);Q=null}c.fn.triggerHandler&&c(s).triggerHandler("ready")}},bindReady:function(){if(!xa){xa=true;if(s.readyState==="complete")return c.ready();if(s.addEventListener){s.addEventListener("DOMContentLoaded",
L,false);A.addEventListener("load",c.ready,false)}else if(s.attachEvent){s.attachEvent("onreadystatechange",L);A.attachEvent("onload",c.ready);var a=false;try{a=A.frameElement==null}catch(b){}s.documentElement.doScroll&&a&&ma()}}},isFunction:function(a){return $.call(a)==="[object Function]"},isArray:function(a){return $.call(a)==="[object Array]"},isPlainObject:function(a){if(!a||$.call(a)!=="[object Object]"||a.nodeType||a.setInterval)return false;if(a.constructor&&!aa.call(a,"constructor")&&!aa.call(a.constructor.prototype,
"isPrototypeOf"))return false;var b;for(b in a);return b===w||aa.call(a,b)},isEmptyObject:function(a){for(var b in a)return false;return true},error:function(a){throw a;},parseJSON:function(a){if(typeof a!=="string"||!a)return null;a=c.trim(a);if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return A.JSON&&A.JSON.parse?A.JSON.parse(a):(new Function("return "+
a))();else c.error("Invalid JSON: "+a)},noop:function(){},globalEval:function(a){if(a&&Va.test(a)){var b=s.getElementsByTagName("head")[0]||s.documentElement,d=s.createElement("script");d.type="text/javascript";if(c.support.scriptEval)d.appendChild(s.createTextNode(a));else d.text=a;b.insertBefore(d,b.firstChild);b.removeChild(d)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){var f,e=0,j=a.length,i=j===w||c.isFunction(a);if(d)if(i)for(f in a){if(b.apply(a[f],
d)===false)break}else for(;e<j;){if(b.apply(a[e++],d)===false)break}else if(i)for(f in a){if(b.call(a[f],f,a[f])===false)break}else for(d=a[0];e<j&&b.call(d,e,d)!==false;d=a[++e]);return a},trim:function(a){return(a||"").replace(Wa,"")},makeArray:function(a,b){b=b||[];if(a!=null)a.length==null||typeof a==="string"||c.isFunction(a)||typeof a!=="function"&&a.setInterval?ba.call(b,a):c.merge(b,a);return b},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var d=0,f=b.length;d<f;d++)if(b[d]===
a)return d;return-1},merge:function(a,b){var d=a.length,f=0;if(typeof b.length==="number")for(var e=b.length;f<e;f++)a[d++]=b[f];else for(;b[f]!==w;)a[d++]=b[f++];a.length=d;return a},grep:function(a,b,d){for(var f=[],e=0,j=a.length;e<j;e++)!d!==!b(a[e],e)&&f.push(a[e]);return f},map:function(a,b,d){for(var f=[],e,j=0,i=a.length;j<i;j++){e=b(a[j],j,d);if(e!=null)f[f.length]=e}return f.concat.apply([],f)},guid:1,proxy:function(a,b,d){if(arguments.length===2)if(typeof b==="string"){d=a;a=d[b];b=w}else if(b&&
!c.isFunction(b)){d=b;b=w}if(!b&&a)b=function(){return a.apply(d||this,arguments)};if(a)b.guid=a.guid=a.guid||b.guid||c.guid++;return b},uaMatch:function(a){a=a.toLowerCase();a=/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version)?[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||!/compatible/.test(a)&&/(mozilla)(?:.*? rv:([\w.]+))?/.exec(a)||[];return{browser:a[1]||"",version:a[2]||"0"}},browser:{}});P=c.uaMatch(P);if(P.browser){c.browser[P.browser]=true;c.browser.version=P.version}if(c.browser.webkit)c.browser.safari=
true;if(ya)c.inArray=function(a,b){return ya.call(b,a)};T=c(s);if(s.addEventListener)L=function(){s.removeEventListener("DOMContentLoaded",L,false);c.ready()};else if(s.attachEvent)L=function(){if(s.readyState==="complete"){s.detachEvent("onreadystatechange",L);c.ready()}};(function(){c.support={};var a=s.documentElement,b=s.createElement("script"),d=s.createElement("div"),f="script"+J();d.style.display="none";d.innerHTML="   <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
var e=d.getElementsByTagName("*"),j=d.getElementsByTagName("a")[0];if(!(!e||!e.length||!j)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(j.getAttribute("style")),hrefNormalized:j.getAttribute("href")==="/a",opacity:/^0.55$/.test(j.style.opacity),cssFloat:!!j.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:s.createElement("select").appendChild(s.createElement("option")).selected,
parentNode:d.removeChild(d.appendChild(s.createElement("div"))).parentNode===null,deleteExpando:true,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};b.type="text/javascript";try{b.appendChild(s.createTextNode("window."+f+"=1;"))}catch(i){}a.insertBefore(b,a.firstChild);if(A[f]){c.support.scriptEval=true;delete A[f]}try{delete b.test}catch(o){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function k(){c.support.noCloneEvent=
false;d.detachEvent("onclick",k)});d.cloneNode(true).fireEvent("onclick")}d=s.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=s.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var k=s.createElement("div");k.style.width=k.style.paddingLeft="1px";s.body.appendChild(k);c.boxModel=c.support.boxModel=k.offsetWidth===2;s.body.removeChild(k).style.display="none"});a=function(k){var n=
s.createElement("div");k="on"+k;var r=k in n;if(!r){n.setAttribute(k,"return;");r=typeof n[k]==="function"}return r};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=e=j=null}})();c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var G="jQuery"+J(),Ya=0,za={};c.extend({cache:{},expando:G,noData:{embed:true,object:true,
applet:true},data:function(a,b,d){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var f=a[G],e=c.cache;if(!f&&typeof b==="string"&&d===w)return null;f||(f=++Ya);if(typeof b==="object"){a[G]=f;e[f]=c.extend(true,{},b)}else if(!e[f]){a[G]=f;e[f]={}}a=e[f];if(d!==w)a[b]=d;return typeof b==="string"?a[b]:a}},removeData:function(a,b){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var d=a[G],f=c.cache,e=f[d];if(b){if(e){delete e[b];c.isEmptyObject(e)&&c.removeData(a)}}else{if(c.support.deleteExpando)delete a[c.expando];
else a.removeAttribute&&a.removeAttribute(c.expando);delete f[d]}}}});c.fn.extend({data:function(a,b){if(typeof a==="undefined"&&this.length)return c.data(this[0]);else if(typeof a==="object")return this.each(function(){c.data(this,a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===w){var f=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(f===w&&this.length)f=c.data(this[0],a);return f===w&&d[1]?this.data(d[0]):f}else return this.trigger("setData"+d[1]+"!",[d[0],b]).each(function(){c.data(this,
a,b)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var f=c.data(a,b);if(!d)return f||[];if(!f||c.isArray(d))f=c.data(a,b,c.makeArray(d));else f.push(d);return f}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),f=d.shift();if(f==="inprogress")f=d.shift();if(f){b==="fx"&&d.unshift("inprogress");f.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===
w)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var Aa=/[\n\t]/g,ca=/\s+/,Za=/\r/g,$a=/href|src|style/,ab=/(button|input)/i,bb=/(button|input|object|select|textarea)/i,
cb=/^(a|area)$/i,Ba=/radio|checkbox/;c.fn.extend({attr:function(a,b){return X(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(n){var r=c(this);r.addClass(a.call(this,n,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1)if(e.className){for(var j=" "+e.className+" ",
i=e.className,o=0,k=b.length;o<k;o++)if(j.indexOf(" "+b[o]+" ")<0)i+=" "+b[o];e.className=c.trim(i)}else e.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(k){var n=c(this);n.removeClass(a.call(this,k,n.attr("class")))});if(a&&typeof a==="string"||a===w)for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1&&e.className)if(a){for(var j=(" "+e.className+" ").replace(Aa," "),i=0,o=b.length;i<o;i++)j=j.replace(" "+b[i]+" ",
" ");e.className=c.trim(j)}else e.className=""}return this},toggleClass:function(a,b){var d=typeof a,f=typeof b==="boolean";if(c.isFunction(a))return this.each(function(e){var j=c(this);j.toggleClass(a.call(this,e,j.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var e,j=0,i=c(this),o=b,k=a.split(ca);e=k[j++];){o=f?o:!i.hasClass(e);i[o?"addClass":"removeClass"](e)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,"__className__",this.className);this.className=
this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(Aa," ").indexOf(a)>-1)return true;return false},val:function(a){if(a===w){var b=this[0];if(b){if(c.nodeName(b,"option"))return(b.attributes.value||{}).specified?b.value:b.text;if(c.nodeName(b,"select")){var d=b.selectedIndex,f=[],e=b.options;b=b.type==="select-one";if(d<0)return null;var j=b?d:0;for(d=b?d+1:e.length;j<d;j++){var i=
e[j];if(i.selected){a=c(i).val();if(b)return a;f.push(a)}}return f}if(Ba.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Za,"")}return w}var o=c.isFunction(a);return this.each(function(k){var n=c(this),r=a;if(this.nodeType===1){if(o)r=a.call(this,k,n.val());if(typeof r==="number")r+="";if(c.isArray(r)&&Ba.test(this.type))this.checked=c.inArray(n.val(),r)>=0;else if(c.nodeName(this,"select")){var u=c.makeArray(r);c("option",this).each(function(){this.selected=
c.inArray(c(this).val(),u)>=0});if(!u.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(a,b,d,f){if(!a||a.nodeType===3||a.nodeType===8)return w;if(f&&b in c.attrFn)return c(a)[b](d);f=a.nodeType!==1||!c.isXMLDoc(a);var e=d!==w;b=f&&c.props[b]||b;if(a.nodeType===1){var j=$a.test(b);if(b in a&&f&&!j){if(e){b==="type"&&ab.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed");
a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&b.specified?b.value:bb.test(a.nodeName)||cb.test(a.nodeName)&&a.href?0:w;return a[b]}if(!c.support.style&&f&&b==="style"){if(e)a.style.cssText=""+d;return a.style.cssText}e&&a.setAttribute(b,""+d);a=!c.support.hrefNormalized&&f&&j?a.getAttribute(b,2):a.getAttribute(b);return a===null?w:a}return c.style(a,b,d)}});var O=/\.(.*)$/,db=function(a){return a.replace(/[^\w\s\.\|`]/g,
function(b){return"\\"+b})};c.event={add:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){if(a.setInterval&&a!==A&&!a.frameElement)a=A;var e,j;if(d.handler){e=d;d=e.handler}if(!d.guid)d.guid=c.guid++;if(j=c.data(a)){var i=j.events=j.events||{},o=j.handle;if(!o)j.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem,arguments):w};o.elem=a;b=b.split(" ");for(var k,n=0,r;k=b[n++];){j=e?c.extend({},e):{handler:d,data:f};if(k.indexOf(".")>-1){r=k.split(".");
k=r.shift();j.namespace=r.slice(0).sort().join(".")}else{r=[];j.namespace=""}j.type=k;j.guid=d.guid;var u=i[k],z=c.event.special[k]||{};if(!u){u=i[k]=[];if(!z.setup||z.setup.call(a,f,r,o)===false)if(a.addEventListener)a.addEventListener(k,o,false);else a.attachEvent&&a.attachEvent("on"+k,o)}if(z.add){z.add.call(a,j);if(!j.handler.guid)j.handler.guid=d.guid}u.push(j);c.event.global[k]=true}a=null}}},global:{},remove:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){var e,j=0,i,o,k,n,r,u,z=c.data(a),
C=z&&z.events;if(z&&C){if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(e in C)c.event.remove(a,e+b)}else{for(b=b.split(" ");e=b[j++];){n=e;i=e.indexOf(".")<0;o=[];if(!i){o=e.split(".");e=o.shift();k=new RegExp("(^|\\.)"+c.map(o.slice(0).sort(),db).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(r=C[e])if(d){n=c.event.special[e]||{};for(B=f||0;B<r.length;B++){u=r[B];if(d.guid===u.guid){if(i||k.test(u.namespace)){f==null&&r.splice(B--,1);n.remove&&n.remove.call(a,u)}if(f!=
null)break}}if(r.length===0||f!=null&&r.length===1){if(!n.teardown||n.teardown.call(a,o)===false)Ca(a,e,z.handle);delete C[e]}}else for(var B=0;B<r.length;B++){u=r[B];if(i||k.test(u.namespace)){c.event.remove(a,n,u.handler,B);r.splice(B--,1)}}}if(c.isEmptyObject(C)){if(b=z.handle)b.elem=null;delete z.events;delete z.handle;c.isEmptyObject(z)&&c.removeData(a)}}}}},trigger:function(a,b,d,f){var e=a.type||a;if(!f){a=typeof a==="object"?a[G]?a:c.extend(c.Event(e),a):c.Event(e);if(e.indexOf("!")>=0){a.type=
e=e.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[e]&&c.each(c.cache,function(){this.events&&this.events[e]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===8)return w;a.result=w;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(f=c.data(d,"handle"))&&f.apply(d,b);f=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+e]&&d["on"+e].apply(d,b)===false)a.result=false}catch(j){}if(!a.isPropagationStopped()&&
f)c.event.trigger(a,b,f,true);else if(!a.isDefaultPrevented()){f=a.target;var i,o=c.nodeName(f,"a")&&e==="click",k=c.event.special[e]||{};if((!k._default||k._default.call(d,a)===false)&&!o&&!(f&&f.nodeName&&c.noData[f.nodeName.toLowerCase()])){try{if(f[e]){if(i=f["on"+e])f["on"+e]=null;c.event.triggered=true;f[e]()}}catch(n){}if(i)f["on"+e]=i;c.event.triggered=false}}},handle:function(a){var b,d,f,e;a=arguments[0]=c.event.fix(a||A.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive;
if(!b){d=a.type.split(".");a.type=d.shift();f=new RegExp("(^|\\.)"+d.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)")}e=c.data(this,"events");d=e[a.type];if(e&&d){d=d.slice(0);e=0;for(var j=d.length;e<j;e++){var i=d[e];if(b||f.test(i.namespace)){a.handler=i.handler;a.data=i.data;a.handleObj=i;i=i.handler.apply(this,arguments);if(i!==w){a.result=i;if(i===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
fix:function(a){if(a[G])return a;var b=a;a=c.Event(b);for(var d=this.props.length,f;d;){f=this.props[--d];a[f]=b[f]}if(!a.target)a.target=a.srcElement||s;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=s.documentElement;d=s.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop||
d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(!a.which&&(a.charCode||a.charCode===0?a.charCode:a.keyCode))a.which=a.charCode||a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==w)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,a.origType,c.extend({},a,{handler:oa}))},remove:function(a){var b=true,d=a.origType.replace(O,"");c.each(c.data(this,
"events").live||[],function(){if(d===this.origType.replace(O,""))return b=false});b&&c.event.remove(this,a.origType,oa)}},beforeunload:{setup:function(a,b,d){if(this.setInterval)this.onbeforeunload=d;return false},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};var Ca=s.removeEventListener?function(a,b,d){a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent=
a;this.type=a.type}else this.type=a;this.timeStamp=J();this[G]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=Z;var a=this.originalEvent;if(a){a.preventDefault&&a.preventDefault();a.returnValue=false}},stopPropagation:function(){this.isPropagationStopped=Z;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=Z;this.stopPropagation()},isDefaultPrevented:Y,isPropagationStopped:Y,
isImmediatePropagationStopped:Y};var Da=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},Ea=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?Ea:Da,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?Ea:Da)}}});if(!c.support.submitBubbles)c.event.special.submit=
{setup:function(){if(this.nodeName.toLowerCase()!=="form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length)return na("submit",this,arguments)});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13)return na("submit",this,arguments)})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}};
if(!c.support.changeBubbles){var da=/textarea|input|select/i,ea,Fa=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(f){return f.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},fa=function(a,b){var d=a.target,f,e;if(!(!da.test(d.nodeName)||d.readOnly)){f=c.data(d,"_change_data");e=Fa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data",
e);if(!(f===w||e===f))if(f!=null||e){a.type="change";return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:fa,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return fa.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return fa.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a,
"_change_data",Fa(a))}},setup:function(){if(this.type==="file")return false;for(var a in ea)c.event.add(this,a+".specialChange",ea[a]);return da.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return da.test(this.nodeName)}};ea=c.event.special.change.filters}s.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(f){f=c.event.fix(f);f.type=b;return c.event.handle.call(this,f)}c.event.special[b]={setup:function(){this.addEventListener(a,
d,true)},teardown:function(){this.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,f,e){if(typeof d==="object"){for(var j in d)this[b](j,f,d[j],e);return this}if(c.isFunction(f)){e=f;f=w}var i=b==="one"?c.proxy(e,function(k){c(this).unbind(k,i);return e.apply(this,arguments)}):e;if(d==="unload"&&b!=="one")this.one(d,f,e);else{j=0;for(var o=this.length;j<o;j++)c.event.add(this[j],d,i,f)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&&
!a.preventDefault)for(var d in a)this.unbind(d,a[d]);else{d=0;for(var f=this.length;d<f;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,f){return this.live(b,d,f,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){a=c.Event(a);a.preventDefault();a.stopPropagation();c.event.trigger(a,b,this[0]);return a.result}},
toggle:function(a){for(var b=arguments,d=1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(f){var e=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,e+1);f.preventDefault();return b[e].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var Ga={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,f,e,j){var i,o=0,k,n,r=j||this.selector,
u=j?this:c(this.context);if(c.isFunction(f)){e=f;f=w}for(d=(d||"").split(" ");(i=d[o++])!=null;){j=O.exec(i);k="";if(j){k=j[0];i=i.replace(O,"")}if(i==="hover")d.push("mouseenter"+k,"mouseleave"+k);else{n=i;if(i==="focus"||i==="blur"){d.push(Ga[i]+k);i+=k}else i=(Ga[i]||i)+k;b==="live"?u.each(function(){c.event.add(this,pa(i,r),{data:f,selector:r,handler:e,origType:i,origHandler:e,preType:n})}):u.unbind(pa(i,r),e)}}return this}});c.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),
function(a,b){c.fn[b]=function(d){return d?this.bind(b,d):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});A.attachEvent&&!A.addEventListener&&A.attachEvent("onunload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}});(function(){function a(g){for(var h="",l,m=0;g[m];m++){l=g[m];if(l.nodeType===3||l.nodeType===4)h+=l.nodeValue;else if(l.nodeType!==8)h+=a(l.childNodes)}return h}function b(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];
if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1&&!p){t.sizcache=l;t.sizset=q}if(t.nodeName.toLowerCase()===h){y=t;break}t=t[g]}m[q]=y}}}function d(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1){if(!p){t.sizcache=l;t.sizset=q}if(typeof h!=="string"){if(t===h){y=true;break}}else if(k.filter(h,[t]).length>0){y=t;break}}t=t[g]}m[q]=y}}}var f=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
e=0,j=Object.prototype.toString,i=false,o=true;[0,0].sort(function(){o=false;return 0});var k=function(g,h,l,m){l=l||[];var q=h=h||s;if(h.nodeType!==1&&h.nodeType!==9)return[];if(!g||typeof g!=="string")return l;for(var p=[],v,t,y,S,H=true,M=x(h),I=g;(f.exec(""),v=f.exec(I))!==null;){I=v[3];p.push(v[1]);if(v[2]){S=v[3];break}}if(p.length>1&&r.exec(g))if(p.length===2&&n.relative[p[0]])t=ga(p[0]+p[1],h);else for(t=n.relative[p[0]]?[h]:k(p.shift(),h);p.length;){g=p.shift();if(n.relative[g])g+=p.shift();
t=ga(g,t)}else{if(!m&&p.length>1&&h.nodeType===9&&!M&&n.match.ID.test(p[0])&&!n.match.ID.test(p[p.length-1])){v=k.find(p.shift(),h,M);h=v.expr?k.filter(v.expr,v.set)[0]:v.set[0]}if(h){v=m?{expr:p.pop(),set:z(m)}:k.find(p.pop(),p.length===1&&(p[0]==="~"||p[0]==="+")&&h.parentNode?h.parentNode:h,M);t=v.expr?k.filter(v.expr,v.set):v.set;if(p.length>0)y=z(t);else H=false;for(;p.length;){var D=p.pop();v=D;if(n.relative[D])v=p.pop();else D="";if(v==null)v=h;n.relative[D](y,v,M)}}else y=[]}y||(y=t);y||k.error(D||
g);if(j.call(y)==="[object Array]")if(H)if(h&&h.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&E(h,y[g])))l.push(t[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&l.push(t[g]);else l.push.apply(l,y);else z(y,l);if(S){k(S,q,l,m);k.uniqueSort(l)}return l};k.uniqueSort=function(g){if(B){i=o;g.sort(B);if(i)for(var h=1;h<g.length;h++)g[h]===g[h-1]&&g.splice(h--,1)}return g};k.matches=function(g,h){return k(g,null,null,h)};k.find=function(g,h,l){var m,q;if(!g)return[];
for(var p=0,v=n.order.length;p<v;p++){var t=n.order[p];if(q=n.leftMatch[t].exec(g)){var y=q[1];q.splice(1,1);if(y.substr(y.length-1)!=="\\"){q[1]=(q[1]||"").replace(/\\/g,"");m=n.find[t](q,h,l);if(m!=null){g=g.replace(n.match[t],"");break}}}}m||(m=h.getElementsByTagName("*"));return{set:m,expr:g}};k.filter=function(g,h,l,m){for(var q=g,p=[],v=h,t,y,S=h&&h[0]&&x(h[0]);g&&h.length;){for(var H in n.filter)if((t=n.leftMatch[H].exec(g))!=null&&t[2]){var M=n.filter[H],I,D;D=t[1];y=false;t.splice(1,1);if(D.substr(D.length-
1)!=="\\"){if(v===p)p=[];if(n.preFilter[H])if(t=n.preFilter[H](t,v,l,p,m,S)){if(t===true)continue}else y=I=true;if(t)for(var U=0;(D=v[U])!=null;U++)if(D){I=M(D,t,U,v);var Ha=m^!!I;if(l&&I!=null)if(Ha)y=true;else v[U]=false;else if(Ha){p.push(D);y=true}}if(I!==w){l||(v=p);g=g.replace(n.match[H],"");if(!y)return[];break}}}if(g===q)if(y==null)k.error(g);else break;q=g}return v};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var n=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF-]|\\.)+)/,
CLASS:/\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}},
relative:{"+":function(g,h){var l=typeof h==="string",m=l&&!/\W/.test(h);l=l&&!m;if(m)h=h.toLowerCase();m=0;for(var q=g.length,p;m<q;m++)if(p=g[m]){for(;(p=p.previousSibling)&&p.nodeType!==1;);g[m]=l||p&&p.nodeName.toLowerCase()===h?p||false:p===h}l&&k.filter(h,g,true)},">":function(g,h){var l=typeof h==="string";if(l&&!/\W/.test(h)){h=h.toLowerCase();for(var m=0,q=g.length;m<q;m++){var p=g[m];if(p){l=p.parentNode;g[m]=l.nodeName.toLowerCase()===h?l:false}}}else{m=0;for(q=g.length;m<q;m++)if(p=g[m])g[m]=
l?p.parentNode:p.parentNode===h;l&&k.filter(h,g,true)}},"":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("parentNode",h,m,g,p,l)},"~":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("previousSibling",h,m,g,p,l)}},find:{ID:function(g,h,l){if(typeof h.getElementById!=="undefined"&&!l)return(g=h.getElementById(g[1]))?[g]:[]},NAME:function(g,h){if(typeof h.getElementsByName!=="undefined"){var l=[];
h=h.getElementsByName(g[1]);for(var m=0,q=h.length;m<q;m++)h[m].getAttribute("name")===g[1]&&l.push(h[m]);return l.length===0?null:l}},TAG:function(g,h){return h.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,h,l,m,q,p){g=" "+g[1].replace(/\\/g,"")+" ";if(p)return g;p=0;for(var v;(v=h[p])!=null;p++)if(v)if(q^(v.className&&(" "+v.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))l||m.push(v);else if(l)h[p]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()},
CHILD:function(g){if(g[1]==="nth"){var h=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=h[1]+(h[2]||1)-0;g[3]=h[3]-0}g[0]=e++;return g},ATTR:function(g,h,l,m,q,p){h=g[1].replace(/\\/g,"");if(!p&&n.attrMap[h])g[1]=n.attrMap[h];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,h,l,m,q){if(g[1]==="not")if((f.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,h);else{g=k.filter(g[3],h,l,true^q);l||m.push.apply(m,
g);return false}else if(n.match.POS.test(g[0])||n.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,h,l){return!!k(l[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)},
text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}},
setFilters:{first:function(g,h){return h===0},last:function(g,h,l,m){return h===m.length-1},even:function(g,h){return h%2===0},odd:function(g,h){return h%2===1},lt:function(g,h,l){return h<l[3]-0},gt:function(g,h,l){return h>l[3]-0},nth:function(g,h,l){return l[3]-0===h},eq:function(g,h,l){return l[3]-0===h}},filter:{PSEUDO:function(g,h,l,m){var q=h[1],p=n.filters[q];if(p)return p(g,l,h,m);else if(q==="contains")return(g.textContent||g.innerText||a([g])||"").indexOf(h[3])>=0;else if(q==="not"){h=
h[3];l=0;for(m=h.length;l<m;l++)if(h[l]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+q)},CHILD:function(g,h){var l=h[1],m=g;switch(l){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(l==="first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":l=h[2];var q=h[3];if(l===1&&q===0)return true;h=h[0];var p=g.parentNode;if(p&&(p.sizcache!==h||!g.nodeIndex)){var v=0;for(m=p.firstChild;m;m=
m.nextSibling)if(m.nodeType===1)m.nodeIndex=++v;p.sizcache=h}g=g.nodeIndex-q;return l===0?g===0:g%l===0&&g/l>=0}},ID:function(g,h){return g.nodeType===1&&g.getAttribute("id")===h},TAG:function(g,h){return h==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===h},CLASS:function(g,h){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(h)>-1},ATTR:function(g,h){var l=h[1];g=n.attrHandle[l]?n.attrHandle[l](g):g[l]!=null?g[l]:g.getAttribute(l);l=g+"";var m=h[2];h=h[4];return g==null?m==="!=":m===
"="?l===h:m==="*="?l.indexOf(h)>=0:m==="~="?(" "+l+" ").indexOf(h)>=0:!h?l&&g!==false:m==="!="?l!==h:m==="^="?l.indexOf(h)===0:m==="$="?l.substr(l.length-h.length)===h:m==="|="?l===h||l.substr(0,h.length+1)===h+"-":false},POS:function(g,h,l,m){var q=n.setFilters[h[2]];if(q)return q(g,l,h,m)}}},r=n.match.POS;for(var u in n.match){n.match[u]=new RegExp(n.match[u].source+/(?![^\[]*\])(?![^\(]*\))/.source);n.leftMatch[u]=new RegExp(/(^(?:.|\r|\n)*?)/.source+n.match[u].source.replace(/\\(\d+)/g,function(g,
h){return"\\"+(h-0+1)}))}var z=function(g,h){g=Array.prototype.slice.call(g,0);if(h){h.push.apply(h,g);return h}return g};try{Array.prototype.slice.call(s.documentElement.childNodes,0)}catch(C){z=function(g,h){h=h||[];if(j.call(g)==="[object Array]")Array.prototype.push.apply(h,g);else if(typeof g.length==="number")for(var l=0,m=g.length;l<m;l++)h.push(g[l]);else for(l=0;g[l];l++)h.push(g[l]);return h}}var B;if(s.documentElement.compareDocumentPosition)B=function(g,h){if(!g.compareDocumentPosition||
!h.compareDocumentPosition){if(g==h)i=true;return g.compareDocumentPosition?-1:1}g=g.compareDocumentPosition(h)&4?-1:g===h?0:1;if(g===0)i=true;return g};else if("sourceIndex"in s.documentElement)B=function(g,h){if(!g.sourceIndex||!h.sourceIndex){if(g==h)i=true;return g.sourceIndex?-1:1}g=g.sourceIndex-h.sourceIndex;if(g===0)i=true;return g};else if(s.createRange)B=function(g,h){if(!g.ownerDocument||!h.ownerDocument){if(g==h)i=true;return g.ownerDocument?-1:1}var l=g.ownerDocument.createRange(),m=
h.ownerDocument.createRange();l.setStart(g,0);l.setEnd(g,0);m.setStart(h,0);m.setEnd(h,0);g=l.compareBoundaryPoints(Range.START_TO_END,m);if(g===0)i=true;return g};(function(){var g=s.createElement("div"),h="script"+(new Date).getTime();g.innerHTML="<a name='"+h+"'/>";var l=s.documentElement;l.insertBefore(g,l.firstChild);if(s.getElementById(h)){n.find.ID=function(m,q,p){if(typeof q.getElementById!=="undefined"&&!p)return(q=q.getElementById(m[1]))?q.id===m[1]||typeof q.getAttributeNode!=="undefined"&&
q.getAttributeNode("id").nodeValue===m[1]?[q]:w:[]};n.filter.ID=function(m,q){var p=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&p&&p.nodeValue===q}}l.removeChild(g);l=g=null})();(function(){var g=s.createElement("div");g.appendChild(s.createComment(""));if(g.getElementsByTagName("*").length>0)n.find.TAG=function(h,l){l=l.getElementsByTagName(h[1]);if(h[1]==="*"){h=[];for(var m=0;l[m];m++)l[m].nodeType===1&&h.push(l[m]);l=h}return l};g.innerHTML="<a href='#'></a>";
if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")n.attrHandle.href=function(h){return h.getAttribute("href",2)};g=null})();s.querySelectorAll&&function(){var g=k,h=s.createElement("div");h.innerHTML="<p class='TEST'></p>";if(!(h.querySelectorAll&&h.querySelectorAll(".TEST").length===0)){k=function(m,q,p,v){q=q||s;if(!v&&q.nodeType===9&&!x(q))try{return z(q.querySelectorAll(m),p)}catch(t){}return g(m,q,p,v)};for(var l in g)k[l]=g[l];h=null}}();
(function(){var g=s.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){n.order.splice(1,0,"CLASS");n.find.CLASS=function(h,l,m){if(typeof l.getElementsByClassName!=="undefined"&&!m)return l.getElementsByClassName(h[1])};g=null}}})();var E=s.compareDocumentPosition?function(g,h){return!!(g.compareDocumentPosition(h)&16)}:
function(g,h){return g!==h&&(g.contains?g.contains(h):true)},x=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false},ga=function(g,h){var l=[],m="",q;for(h=h.nodeType?[h]:h;q=n.match.PSEUDO.exec(g);){m+=q[0];g=g.replace(n.match.PSEUDO,"")}g=n.relative[g]?g+"*":g;q=0;for(var p=h.length;q<p;q++)k(g,h[q],l);return k.filter(m,l)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=a;c.isXMLDoc=x;c.contains=E})();var eb=/Until$/,fb=/^(?:parents|prevUntil|prevAll)/,
gb=/,/;R=Array.prototype.slice;var Ia=function(a,b,d){if(c.isFunction(b))return c.grep(a,function(e,j){return!!b.call(e,j,e)===d});else if(b.nodeType)return c.grep(a,function(e){return e===b===d});else if(typeof b==="string"){var f=c.grep(a,function(e){return e.nodeType===1});if(Ua.test(b))return c.filter(b,f,!d);else b=c.filter(b,f)}return c.grep(a,function(e){return c.inArray(e,b)>=0===d})};c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,f=0,e=this.length;f<e;f++){d=b.length;
c.find(a,this[f],b);if(f>0)for(var j=d;j<b.length;j++)for(var i=0;i<d;i++)if(b[i]===b[j]){b.splice(j--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,f=b.length;d<f;d++)if(c.contains(this,b[d]))return true})},not:function(a){return this.pushStack(Ia(this,a,false),"not",a)},filter:function(a){return this.pushStack(Ia(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){if(c.isArray(a)){var d=[],f=this[0],e,j=
{},i;if(f&&a.length){e=0;for(var o=a.length;e<o;e++){i=a[e];j[i]||(j[i]=c.expr.match.POS.test(i)?c(i,b||this.context):i)}for(;f&&f.ownerDocument&&f!==b;){for(i in j){e=j[i];if(e.jquery?e.index(f)>-1:c(f).is(e)){d.push({selector:i,elem:f});delete j[i]}}f=f.parentNode}}return d}var k=c.expr.match.POS.test(a)?c(a,b||this.context):null;return this.map(function(n,r){for(;r&&r.ownerDocument&&r!==b;){if(k?k.index(r)>-1:c(r).is(a))return r;r=r.parentNode}return null})},index:function(a){if(!a||typeof a===
"string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){a=typeof a==="string"?c(a,b||this.context):c.makeArray(a);b=c.merge(this.get(),a);return this.pushStack(qa(a[0])||qa(b[0])?b:c.unique(b))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode",
d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")?
a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,b){c.fn[a]=function(d,f){var e=c.map(this,b,d);eb.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e):e;if((this.length>1||gb.test(f))&&fb.test(a))e=e.reverse();return this.pushStack(e,a,R.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return c.find.matches(a,b)},dir:function(a,b,d){var f=[];for(a=a[b];a&&a.nodeType!==9&&(d===w||a.nodeType!==1||!c(a).is(d));){a.nodeType===
1&&f.push(a);a=a[b]}return f},nth:function(a,b,d){b=b||1;for(var f=0;a;a=a[d])if(a.nodeType===1&&++f===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var Ja=/ jQuery\d+="(?:\d+|null)"/g,V=/^\s+/,Ka=/(<([\w:]+)[^>]*?)\/>/g,hb=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,La=/<([\w:]+)/,ib=/<tbody/i,jb=/<|&#?\w+;/,ta=/<script|<object|<embed|<option|<style/i,ua=/checked\s*(?:[^=]|=\s*.checked.)/i,Ma=function(a,b,d){return hb.test(d)?
a:b+"></"+d+">"},F={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};F.optgroup=F.option;F.tbody=F.tfoot=F.colgroup=F.caption=F.thead;F.th=F.td;if(!c.support.htmlSerialize)F._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d=
c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==w)return this.empty().append((this[0]&&this[0].ownerDocument||s).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this},
wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})},
prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,
this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,f;(f=this[d])!=null;d++)if(!a||c.filter(a,[f]).length){if(!b&&f.nodeType===1){c.cleanData(f.getElementsByTagName("*"));c.cleanData([f])}f.parentNode&&f.parentNode.removeChild(f)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild);
return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,f=this.ownerDocument;if(!d){d=f.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(Ja,"").replace(/=([^="'>\s]+\/)>/g,'="$1">').replace(V,"")],f)[0]}else return this.cloneNode(true)});if(a===true){ra(this,b);ra(this.find("*"),b.find("*"))}return b},html:function(a){if(a===w)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Ja,
""):null;else if(typeof a==="string"&&!ta.test(a)&&(c.support.leadingWhitespace||!V.test(a))&&!F[(La.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Ka,Ma);try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(f){this.empty().append(a)}}else c.isFunction(a)?this.each(function(e){var j=c(this),i=j.html();j.empty().append(function(){return a.call(this,e,i)})}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&
this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d=c(this),f=d.html();d.replaceWith(a.call(this,b,f))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){function f(u){return c.nodeName(u,"table")?u.getElementsByTagName("tbody")[0]||
u.appendChild(u.ownerDocument.createElement("tbody")):u}var e,j,i=a[0],o=[],k;if(!c.support.checkClone&&arguments.length===3&&typeof i==="string"&&ua.test(i))return this.each(function(){c(this).domManip(a,b,d,true)});if(c.isFunction(i))return this.each(function(u){var z=c(this);a[0]=i.call(this,u,b?z.html():w);z.domManip(a,b,d)});if(this[0]){e=i&&i.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:sa(a,this,o);k=e.fragment;if(j=k.childNodes.length===
1?(k=k.firstChild):k.firstChild){b=b&&c.nodeName(j,"tr");for(var n=0,r=this.length;n<r;n++)d.call(b?f(this[n],j):this[n],n>0||e.cacheable||this.length>1?k.cloneNode(true):k)}o.length&&c.each(o,Qa)}return this}});c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var f=[];d=c(d);var e=this.length===1&&this[0].parentNode;if(e&&e.nodeType===11&&e.childNodes.length===1&&d.length===1){d[b](this[0]);
return this}else{e=0;for(var j=d.length;e<j;e++){var i=(e>0?this.clone(true):this).get();c.fn[b].apply(c(d[e]),i);f=f.concat(i)}return this.pushStack(f,a,d.selector)}}});c.extend({clean:function(a,b,d,f){b=b||s;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||s;for(var e=[],j=0,i;(i=a[j])!=null;j++){if(typeof i==="number")i+="";if(i){if(typeof i==="string"&&!jb.test(i))i=b.createTextNode(i);else if(typeof i==="string"){i=i.replace(Ka,Ma);var o=(La.exec(i)||["",
""])[1].toLowerCase(),k=F[o]||F._default,n=k[0],r=b.createElement("div");for(r.innerHTML=k[1]+i+k[2];n--;)r=r.lastChild;if(!c.support.tbody){n=ib.test(i);o=o==="table"&&!n?r.firstChild&&r.firstChild.childNodes:k[1]==="<table>"&&!n?r.childNodes:[];for(k=o.length-1;k>=0;--k)c.nodeName(o[k],"tbody")&&!o[k].childNodes.length&&o[k].parentNode.removeChild(o[k])}!c.support.leadingWhitespace&&V.test(i)&&r.insertBefore(b.createTextNode(V.exec(i)[0]),r.firstChild);i=r.childNodes}if(i.nodeType)e.push(i);else e=
c.merge(e,i)}}if(d)for(j=0;e[j];j++)if(f&&c.nodeName(e[j],"script")&&(!e[j].type||e[j].type.toLowerCase()==="text/javascript"))f.push(e[j].parentNode?e[j].parentNode.removeChild(e[j]):e[j]);else{e[j].nodeType===1&&e.splice.apply(e,[j+1,0].concat(c.makeArray(e[j].getElementsByTagName("script"))));d.appendChild(e[j])}return e},cleanData:function(a){for(var b,d,f=c.cache,e=c.event.special,j=c.support.deleteExpando,i=0,o;(o=a[i])!=null;i++)if(d=o[c.expando]){b=f[d];if(b.events)for(var k in b.events)e[k]?
c.event.remove(o,k):Ca(o,k,b.handle);if(j)delete o[c.expando];else o.removeAttribute&&o.removeAttribute(c.expando);delete f[d]}}});var kb=/z-?index|font-?weight|opacity|zoom|line-?height/i,Na=/alpha\([^)]*\)/,Oa=/opacity=([^)]*)/,ha=/float/i,ia=/-([a-z])/ig,lb=/([A-Z])/g,mb=/^-?\d+(?:px)?$/i,nb=/^-?\d/,ob={position:"absolute",visibility:"hidden",display:"block"},pb=["Left","Right"],qb=["Top","Bottom"],rb=s.defaultView&&s.defaultView.getComputedStyle,Pa=c.support.cssFloat?"cssFloat":"styleFloat",ja=
function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){return X(this,a,b,true,function(d,f,e){if(e===w)return c.curCSS(d,f);if(typeof e==="number"&&!kb.test(f))e+="px";c.style(d,f,e)})};c.extend({style:function(a,b,d){if(!a||a.nodeType===3||a.nodeType===8)return w;if((b==="width"||b==="height")&&parseFloat(d)<0)d=w;var f=a.style||a,e=d!==w;if(!c.support.opacity&&b==="opacity"){if(e){f.zoom=1;b=parseInt(d,10)+""==="NaN"?"":"alpha(opacity="+d*100+")";a=f.filter||c.curCSS(a,"filter")||"";f.filter=
Na.test(a)?a.replace(Na,b):b}return f.filter&&f.filter.indexOf("opacity=")>=0?parseFloat(Oa.exec(f.filter)[1])/100+"":""}if(ha.test(b))b=Pa;b=b.replace(ia,ja);if(e)f[b]=d;return f[b]},css:function(a,b,d,f){if(b==="width"||b==="height"){var e,j=b==="width"?pb:qb;function i(){e=b==="width"?a.offsetWidth:a.offsetHeight;f!=="border"&&c.each(j,function(){f||(e-=parseFloat(c.curCSS(a,"padding"+this,true))||0);if(f==="margin")e+=parseFloat(c.curCSS(a,"margin"+this,true))||0;else e-=parseFloat(c.curCSS(a,
"border"+this+"Width",true))||0})}a.offsetWidth!==0?i():c.swap(a,ob,i);return Math.max(0,Math.round(e))}return c.curCSS(a,b,d)},curCSS:function(a,b,d){var f,e=a.style;if(!c.support.opacity&&b==="opacity"&&a.currentStyle){f=Oa.test(a.currentStyle.filter||"")?parseFloat(RegExp.$1)/100+"":"";return f===""?"1":f}if(ha.test(b))b=Pa;if(!d&&e&&e[b])f=e[b];else if(rb){if(ha.test(b))b="float";b=b.replace(lb,"-$1").toLowerCase();e=a.ownerDocument.defaultView;if(!e)return null;if(a=e.getComputedStyle(a,null))f=
a.getPropertyValue(b);if(b==="opacity"&&f==="")f="1"}else if(a.currentStyle){d=b.replace(ia,ja);f=a.currentStyle[b]||a.currentStyle[d];if(!mb.test(f)&&nb.test(f)){b=e.left;var j=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;e.left=d==="fontSize"?"1em":f||0;f=e.pixelLeft+"px";e.left=b;a.runtimeStyle.left=j}}return f},swap:function(a,b,d){var f={};for(var e in b){f[e]=a.style[e];a.style[e]=b[e]}d.call(a);for(e in b)a.style[e]=f[e]}});if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=
a.offsetWidth,d=a.offsetHeight,f=a.nodeName.toLowerCase()==="tr";return b===0&&d===0&&!f?true:b>0&&d>0&&!f?false:c.curCSS(a,"display")==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var sb=J(),tb=/<script(.|\s)*?\/script>/gi,ub=/select|textarea/i,vb=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,N=/=\?(&|$)/,ka=/\?/,wb=/(\?|&)_=.*?(&|$)/,xb=/^(\w+:)?\/\/([^\/?#]+)/,yb=/%20/g,zb=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!==
"string")return zb.call(this,a);else if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var e=a.slice(f,a.length);a=a.slice(0,f)}f="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b==="object"){b=c.param(b,c.ajaxSettings.traditional);f="POST"}var j=this;c.ajax({url:a,type:f,dataType:"html",data:b,complete:function(i,o){if(o==="success"||o==="notmodified")j.html(e?c("<div />").append(i.responseText.replace(tb,"")).find(e):i.responseText);d&&j.each(d,[i.responseText,o,i])}});return this},
serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ub.test(this.nodeName)||vb.test(this.type))}).map(function(a,b){a=c(this).val();return a==null?null:c.isArray(a)?c.map(a,function(d){return{name:b.name,value:d}}):{name:b.name,value:a}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),
function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:f})},getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:f})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href,
global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:A.XMLHttpRequest&&(A.location.protocol!=="file:"||!A.ActiveXObject)?function(){return new A.XMLHttpRequest}:function(){try{return new A.ActiveXObject("Microsoft.XMLHTTP")}catch(a){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(a){function b(){e.success&&
e.success.call(k,o,i,x);e.global&&f("ajaxSuccess",[x,e])}function d(){e.complete&&e.complete.call(k,x,i);e.global&&f("ajaxComplete",[x,e]);e.global&&!--c.active&&c.event.trigger("ajaxStop")}function f(q,p){(e.context?c(e.context):c.event).trigger(q,p)}var e=c.extend(true,{},c.ajaxSettings,a),j,i,o,k=a&&a.context||e,n=e.type.toUpperCase();if(e.data&&e.processData&&typeof e.data!=="string")e.data=c.param(e.data,e.traditional);if(e.dataType==="jsonp"){if(n==="GET")N.test(e.url)||(e.url+=(ka.test(e.url)?
"&":"?")+(e.jsonp||"callback")+"=?");else if(!e.data||!N.test(e.data))e.data=(e.data?e.data+"&":"")+(e.jsonp||"callback")+"=?";e.dataType="json"}if(e.dataType==="json"&&(e.data&&N.test(e.data)||N.test(e.url))){j=e.jsonpCallback||"jsonp"+sb++;if(e.data)e.data=(e.data+"").replace(N,"="+j+"$1");e.url=e.url.replace(N,"="+j+"$1");e.dataType="script";A[j]=A[j]||function(q){o=q;b();d();A[j]=w;try{delete A[j]}catch(p){}z&&z.removeChild(C)}}if(e.dataType==="script"&&e.cache===null)e.cache=false;if(e.cache===
false&&n==="GET"){var r=J(),u=e.url.replace(wb,"$1_="+r+"$2");e.url=u+(u===e.url?(ka.test(e.url)?"&":"?")+"_="+r:"")}if(e.data&&n==="GET")e.url+=(ka.test(e.url)?"&":"?")+e.data;e.global&&!c.active++&&c.event.trigger("ajaxStart");r=(r=xb.exec(e.url))&&(r[1]&&r[1]!==location.protocol||r[2]!==location.host);if(e.dataType==="script"&&n==="GET"&&r){var z=s.getElementsByTagName("head")[0]||s.documentElement,C=s.createElement("script");C.src=e.url;if(e.scriptCharset)C.charset=e.scriptCharset;if(!j){var B=
false;C.onload=C.onreadystatechange=function(){if(!B&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){B=true;b();d();C.onload=C.onreadystatechange=null;z&&C.parentNode&&z.removeChild(C)}}}z.insertBefore(C,z.firstChild);return w}var E=false,x=e.xhr();if(x){e.username?x.open(n,e.url,e.async,e.username,e.password):x.open(n,e.url,e.async);try{if(e.data||a&&a.contentType)x.setRequestHeader("Content-Type",e.contentType);if(e.ifModified){c.lastModified[e.url]&&x.setRequestHeader("If-Modified-Since",
c.lastModified[e.url]);c.etag[e.url]&&x.setRequestHeader("If-None-Match",c.etag[e.url])}r||x.setRequestHeader("X-Requested-With","XMLHttpRequest");x.setRequestHeader("Accept",e.dataType&&e.accepts[e.dataType]?e.accepts[e.dataType]+", */*":e.accepts._default)}catch(ga){}if(e.beforeSend&&e.beforeSend.call(k,x,e)===false){e.global&&!--c.active&&c.event.trigger("ajaxStop");x.abort();return false}e.global&&f("ajaxSend",[x,e]);var g=x.onreadystatechange=function(q){if(!x||x.readyState===0||q==="abort"){E||
d();E=true;if(x)x.onreadystatechange=c.noop}else if(!E&&x&&(x.readyState===4||q==="timeout")){E=true;x.onreadystatechange=c.noop;i=q==="timeout"?"timeout":!c.httpSuccess(x)?"error":e.ifModified&&c.httpNotModified(x,e.url)?"notmodified":"success";var p;if(i==="success")try{o=c.httpData(x,e.dataType,e)}catch(v){i="parsererror";p=v}if(i==="success"||i==="notmodified")j||b();else c.handleError(e,x,i,p);d();q==="timeout"&&x.abort();if(e.async)x=null}};try{var h=x.abort;x.abort=function(){x&&h.call(x);
g("abort")}}catch(l){}e.async&&e.timeout>0&&setTimeout(function(){x&&!E&&g("timeout")},e.timeout);try{x.send(n==="POST"||n==="PUT"||n==="DELETE"?e.data:null)}catch(m){c.handleError(e,x,null,m);d()}e.async||g();return x}},handleError:function(a,b,d,f){if(a.error)a.error.call(a.context||a,b,d,f);if(a.global)(a.context?c(a.context):c.event).trigger("ajaxError",[b,a,f])},active:0,httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status===
1223||a.status===0}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),f=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(f)c.etag[b]=f;return a.status===304||a.status===0},httpData:function(a,b,d){var f=a.getResponseHeader("content-type")||"",e=b==="xml"||!b&&f.indexOf("xml")>=0;a=e?a.responseXML:a.responseText;e&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b===
"json"||!b&&f.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&f.indexOf("javascript")>=0)c.globalEval(a);return a},param:function(a,b){function d(i,o){if(c.isArray(o))c.each(o,function(k,n){b||/\[\]$/.test(i)?f(i,n):d(i+"["+(typeof n==="object"||c.isArray(n)?k:"")+"]",n)});else!b&&o!=null&&typeof o==="object"?c.each(o,function(k,n){d(i+"["+k+"]",n)}):f(i,o)}function f(i,o){o=c.isFunction(o)?o():o;e[e.length]=encodeURIComponent(i)+"="+encodeURIComponent(o)}var e=[];if(b===w)b=c.ajaxSettings.traditional;
if(c.isArray(a)||a.jquery)c.each(a,function(){f(this.name,this.value)});else for(var j in a)d(j,a[j]);return e.join("&").replace(yb,"+")}});var la={},Ab=/toggle|show|hide/,Bb=/^([+-]=)?([\d+-.]+)(.*)$/,W,va=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b){if(a||a===0)return this.animate(K("show",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");
this[a].style.display=d||"";if(c.css(this[a],"display")==="none"){d=this[a].nodeName;var f;if(la[d])f=la[d];else{var e=c("<"+d+" />").appendTo("body");f=e.css("display");if(f==="none")f="block";e.remove();la[d]=f}c.data(this[a],"olddisplay",f)}}a=0;for(b=this.length;a<b;a++)this[a].style.display=c.data(this[a],"olddisplay")||"";return this}},hide:function(a,b){if(a||a===0)return this.animate(K("hide",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");!d&&d!=="none"&&c.data(this[a],
"olddisplay",c.css(this[a],"display"))}a=0;for(b=this.length;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b){var d=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||d?this.each(function(){var f=d?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(K("toggle",3),a,b);return this},fadeTo:function(a,b,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d)},
animate:function(a,b,d,f){var e=c.speed(b,d,f);if(c.isEmptyObject(a))return this.each(e.complete);return this[e.queue===false?"each":"queue"](function(){var j=c.extend({},e),i,o=this.nodeType===1&&c(this).is(":hidden"),k=this;for(i in a){var n=i.replace(ia,ja);if(i!==n){a[n]=a[i];delete a[i];i=n}if(a[i]==="hide"&&o||a[i]==="show"&&!o)return j.complete.call(this);if((i==="height"||i==="width")&&this.style){j.display=c.css(this,"display");j.overflow=this.style.overflow}if(c.isArray(a[i])){(j.specialEasing=
j.specialEasing||{})[i]=a[i][1];a[i]=a[i][0]}}if(j.overflow!=null)this.style.overflow="hidden";j.curAnim=c.extend({},a);c.each(a,function(r,u){var z=new c.fx(k,j,r);if(Ab.test(u))z[u==="toggle"?o?"show":"hide":u](a);else{var C=Bb.exec(u),B=z.cur(true)||0;if(C){u=parseFloat(C[2]);var E=C[3]||"px";if(E!=="px"){k.style[r]=(u||1)+E;B=(u||1)/z.cur(true)*B;k.style[r]=B+E}if(C[1])u=(C[1]==="-="?-1:1)*u+B;z.custom(B,u,E)}else z.custom(B,u,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);
this.each(function(){for(var f=d.length-1;f>=0;f--)if(d[f].elem===this){b&&d[f](true);d.splice(f,1)}});b||this.dequeue();return this}});c.each({slideDown:K("show",1),slideUp:K("hide",1),slideToggle:K("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,f){return this.animate(b,d,f)}});c.extend({speed:function(a,b,d){var f=a&&typeof a==="object"?a:{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};f.duration=c.fx.off?0:typeof f.duration===
"number"?f.duration:c.fx.speeds[f.duration]||c.fx.speeds._default;f.old=f.complete;f.complete=function(){f.queue!==false&&c(this).dequeue();c.isFunction(f.old)&&f.old.call(this)};return f},easing:{linear:function(a,b,d,f){return d+f*a},swing:function(a,b,d,f){return(-Math.cos(a*Math.PI)/2+0.5)*f+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]||
c.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style)this.elem.style.display="block"},cur:function(a){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];return(a=parseFloat(c.css(this.elem,this.prop,a)))&&a>-10000?a:parseFloat(c.curCSS(this.elem,this.prop))||0},custom:function(a,b,d){function f(j){return e.step(j)}this.startTime=J();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;
this.pos=this.state=0;var e=this;f.elem=this.elem;if(f()&&c.timers.push(f)&&!W)W=setInterval(c.fx.tick,13)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a){var b=J(),d=true;if(a||b>=this.options.duration+this.startTime){this.now=
this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var f in this.options.curAnim)if(this.options.curAnim[f]!==true)d=false;if(d){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;a=c.data(this.elem,"olddisplay");this.elem.style.display=a?a:this.options.display;if(c.css(this.elem,"display")==="none")this.elem.style.display="block"}this.options.hide&&c(this.elem).hide();if(this.options.hide||this.options.show)for(var e in this.options.curAnim)c.style(this.elem,
e,this.options.orig[e]);this.options.complete.call(this.elem)}return false}else{e=b-this.startTime;this.state=e/this.options.duration;a=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||a](this.state,e,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||
c.fx.stop()},stop:function(){clearInterval(W);W=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===b.elem}).length};c.fn.offset="getBoundingClientRect"in s.documentElement?
function(a){var b=this[0];if(a)return this.each(function(e){c.offset.setOffset(this,a,e)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);var d=b.getBoundingClientRect(),f=b.ownerDocument;b=f.body;f=f.documentElement;return{top:d.top+(self.pageYOffset||c.support.boxModel&&f.scrollTop||b.scrollTop)-(f.clientTop||b.clientTop||0),left:d.left+(self.pageXOffset||c.support.boxModel&&f.scrollLeft||b.scrollLeft)-(f.clientLeft||b.clientLeft||0)}}:function(a){var b=
this[0];if(a)return this.each(function(r){c.offset.setOffset(this,a,r)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d=b.offsetParent,f=b,e=b.ownerDocument,j,i=e.documentElement,o=e.body;f=(e=e.defaultView)?e.getComputedStyle(b,null):b.currentStyle;for(var k=b.offsetTop,n=b.offsetLeft;(b=b.parentNode)&&b!==o&&b!==i;){if(c.offset.supportsFixedPosition&&f.position==="fixed")break;j=e?e.getComputedStyle(b,null):b.currentStyle;
k-=b.scrollTop;n-=b.scrollLeft;if(b===d){k+=b.offsetTop;n+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(b.nodeName))){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=d;d=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&j.overflow!=="visible"){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=j}if(f.position==="relative"||f.position==="static"){k+=o.offsetTop;n+=o.offsetLeft}if(c.offset.supportsFixedPosition&&
f.position==="fixed"){k+=Math.max(i.scrollTop,o.scrollTop);n+=Math.max(i.scrollLeft,o.scrollLeft)}return{top:k,left:n}};c.offset={initialize:function(){var a=s.body,b=s.createElement("div"),d,f,e,j=parseFloat(c.curCSS(a,"marginTop",true))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";
a.insertBefore(b,a.firstChild);d=b.firstChild;f=d.firstChild;e=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=f.offsetTop!==5;this.doesAddBorderForTableAndCells=e.offsetTop===5;f.style.position="fixed";f.style.top="20px";this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15;f.style.position=f.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==j;a.removeChild(b);
c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.curCSS(a,"marginTop",true))||0;d+=parseFloat(c.curCSS(a,"marginLeft",true))||0}return{top:b,left:d}},setOffset:function(a,b,d){if(/static/.test(c.curCSS(a,"position")))a.style.position="relative";var f=c(a),e=f.offset(),j=parseInt(c.curCSS(a,"top",true),10)||0,i=parseInt(c.curCSS(a,"left",true),10)||0;if(c.isFunction(b))b=b.call(a,
d,e);d={top:b.top-e.top+j,left:b.left-e.left+i};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{top:d.top-
f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||s.body;a&&!/^body|html$/i.test(a.nodeName)&&c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(f){var e=this[0],j;if(!e)return null;if(f!==w)return this.each(function(){if(j=wa(this))j.scrollTo(!a?f:c(j).scrollLeft(),a?f:c(j).scrollTop());else this[d]=f});else return(j=wa(e))?"pageXOffset"in j?j[a?"pageYOffset":
"pageXOffset"]:c.support.boxModel&&j.document.documentElement[d]||j.document.body[d]:e[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;if(c.isFunction(f))return this.each(function(j){var i=c(this);i[d](f.call(this,j,i[d]()))});return"scrollTo"in
e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]||e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===w?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});A.jQuery=A.$=c})(window);

/*!
 * jQuery UI 1.8.1
 *
 * Copyright (c) 2010 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */
jQuery.ui||function(c){c.ui={version:"1.8.1",plugin:{add:function(a,b,d){a=c.ui[a].prototype;for(var e in d){a.plugins[e]=a.plugins[e]||[];a.plugins[e].push([b,d[e]])}},call:function(a,b,d){if((b=a.plugins[b])&&a.element[0].parentNode)for(var e=0;e<b.length;e++)a.options[b[e][0]]&&b[e][1].apply(a.element,d)}},contains:function(a,b){return document.compareDocumentPosition?a.compareDocumentPosition(b)&16:a!==b&&a.contains(b)},hasScroll:function(a,b){if(c(a).css("overflow")=="hidden")return false;
b=b&&b=="left"?"scrollLeft":"scrollTop";var d=false;if(a[b]>0)return true;a[b]=1;d=a[b]>0;a[b]=0;return d},isOverAxis:function(a,b,d){return a>b&&a<b+d},isOver:function(a,b,d,e,f,g){return c.ui.isOverAxis(a,d,f)&&c.ui.isOverAxis(b,e,g)},keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,
PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38}};c.fn.extend({_focus:c.fn.focus,focus:function(a,b){return typeof a==="number"?this.each(function(){var d=this;setTimeout(function(){c(d).focus();b&&b.call(d)},a)}):this._focus.apply(this,arguments)},enableSelection:function(){return this.attr("unselectable","off").css("MozUserSelect","")},disableSelection:function(){return this.attr("unselectable","on").css("MozUserSelect","none")},scrollParent:function(){var a;a=c.browser.msie&&/(static|relative)/.test(this.css("position"))||
/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(c.curCSS(this,"position",1))&&/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0);return/fixed/.test(this.css("position"))||!a.length?c(document):a},zIndex:function(a){if(a!==
undefined)return this.css("zIndex",a);if(this.length){a=c(this[0]);for(var b;a.length&&a[0]!==document;){b=a.css("position");if(b=="absolute"||b=="relative"||b=="fixed"){b=parseInt(a.css("zIndex"));if(!isNaN(b)&&b!=0)return b}a=a.parent()}}return 0}});c.extend(c.expr[":"],{data:function(a,b,d){return!!c.data(a,d[3])},focusable:function(a){var b=a.nodeName.toLowerCase(),d=c.attr(a,"tabindex");return(/input|select|textarea|button|object/.test(b)?!a.disabled:"a"==b||"area"==b?a.href||!isNaN(d):!isNaN(d))&&
!c(a)["area"==b?"parents":"closest"](":hidden").length},tabbable:function(a){var b=c.attr(a,"tabindex");return(isNaN(b)||b>=0)&&c(a).is(":focusable")}})}(jQuery);
(function(b){var j=b.fn.remove;b.fn.remove=function(a,c){return this.each(function(){if(!c)if(!a||b.filter(a,[this]).length)b("*",this).add(this).each(function(){b(this).triggerHandler("remove")});return j.call(b(this),a,c)})};b.widget=function(a,c,d){var e=a.split(".")[0],f;a=a.split(".")[1];f=e+"-"+a;if(!d){d=c;c=b.Widget}b.expr[":"][f]=function(h){return!!b.data(h,a)};b[e]=b[e]||{};b[e][a]=function(h,g){arguments.length&&this._createWidget(h,g)};c=new c;c.options=b.extend({},c.options);b[e][a].prototype=
b.extend(true,c,{namespace:e,widgetName:a,widgetEventPrefix:b[e][a].prototype.widgetEventPrefix||a,widgetBaseClass:f},d);b.widget.bridge(a,b[e][a])};b.widget.bridge=function(a,c){b.fn[a]=function(d){var e=typeof d==="string",f=Array.prototype.slice.call(arguments,1),h=this;d=!e&&f.length?b.extend.apply(null,[true,d].concat(f)):d;if(e&&d.substring(0,1)==="_")return h;e?this.each(function(){var g=b.data(this,a),i=g&&b.isFunction(g[d])?g[d].apply(g,f):g;if(i!==g&&i!==undefined){h=i;return false}}):this.each(function(){var g=
b.data(this,a);if(g){d&&g.option(d);g._init()}else b.data(this,a,new c(d,this))});return h}};b.Widget=function(a,c){arguments.length&&this._createWidget(a,c)};b.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:false},_createWidget:function(a,c){this.element=b(c).data(this.widgetName,this);this.options=b.extend(true,{},this.options,b.metadata&&b.metadata.get(c)[this.widgetName],a);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy()});this._create();
this._init()},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName);this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled")},widget:function(){return this.element},option:function(a,c){var d=a,e=this;if(arguments.length===0)return b.extend({},e.options);if(typeof a==="string"){if(c===undefined)return this.options[a];d={};d[a]=c}b.each(d,function(f,
h){e._setOption(f,h)});return e},_setOption:function(a,c){this.options[a]=c;if(a==="disabled")this.widget()[c?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",c);return this},enable:function(){return this._setOption("disabled",false)},disable:function(){return this._setOption("disabled",true)},_trigger:function(a,c,d){var e=this.options[a];c=b.Event(c);c.type=(a===this.widgetEventPrefix?a:this.widgetEventPrefix+a).toLowerCase();d=d||{};if(c.originalEvent){a=
b.event.props.length;for(var f;a;){f=b.event.props[--a];c[f]=c.originalEvent[f]}}this.element.trigger(c,d);return!(b.isFunction(e)&&e.call(this.element[0],c,d)===false||c.isDefaultPrevented())}}})(jQuery);
(function(c){c.widget("ui.mouse",{options:{cancel:":input,option",distance:1,delay:0},_mouseInit:function(){var a=this;this.element.bind("mousedown."+this.widgetName,function(b){return a._mouseDown(b)}).bind("click."+this.widgetName,function(b){if(a._preventClickEvent){a._preventClickEvent=false;b.stopImmediatePropagation();return false}});this.started=false},_mouseDestroy:function(){this.element.unbind("."+this.widgetName)},_mouseDown:function(a){a.originalEvent=a.originalEvent||{};if(!a.originalEvent.mouseHandled){this._mouseStarted&&
this._mouseUp(a);this._mouseDownEvent=a;var b=this,e=a.which==1,f=typeof this.options.cancel=="string"?c(a.target).parents().add(a.target).filter(this.options.cancel).length:false;if(!e||f||!this._mouseCapture(a))return true;this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet)this._mouseDelayTimer=setTimeout(function(){b.mouseDelayMet=true},this.options.delay);if(this._mouseDistanceMet(a)&&this._mouseDelayMet(a)){this._mouseStarted=this._mouseStart(a)!==false;if(!this._mouseStarted){a.preventDefault();
return true}}this._mouseMoveDelegate=function(d){return b._mouseMove(d)};this._mouseUpDelegate=function(d){return b._mouseUp(d)};c(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);c.browser.safari||a.preventDefault();return a.originalEvent.mouseHandled=true}},_mouseMove:function(a){if(c.browser.msie&&!a.button)return this._mouseUp(a);if(this._mouseStarted){this._mouseDrag(a);return a.preventDefault()}if(this._mouseDistanceMet(a)&&
this._mouseDelayMet(a))(this._mouseStarted=this._mouseStart(this._mouseDownEvent,a)!==false)?this._mouseDrag(a):this._mouseUp(a);return!this._mouseStarted},_mouseUp:function(a){c(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;this._preventClickEvent=a.target==this._mouseDownEvent.target;this._mouseStop(a)}return false},_mouseDistanceMet:function(a){return Math.max(Math.abs(this._mouseDownEvent.pageX-
a.pageX),Math.abs(this._mouseDownEvent.pageY-a.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return true}})})(jQuery);
(function(d){d.widget("ui.draggable",d.ui.mouse,{widgetEventPrefix:"drag",options:{addClasses:true,appendTo:"parent",axis:false,connectToSortable:false,containment:false,cursor:"auto",cursorAt:false,grid:false,handle:false,helper:"original",iframeFix:false,opacity:false,refreshPositions:false,revert:false,revertDuration:500,scope:"default",scroll:true,scrollSensitivity:20,scrollSpeed:20,snap:false,snapMode:"both",snapTolerance:20,stack:false,zIndex:false},_create:function(){if(this.options.helper==
"original"&&!/^(?:r|a|f)/.test(this.element.css("position")))this.element[0].style.position="relative";this.options.addClasses&&this.element.addClass("ui-draggable");this.options.disabled&&this.element.addClass("ui-draggable-disabled");this._mouseInit()},destroy:function(){if(this.element.data("draggable")){this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled");this._mouseDestroy();return this}},_mouseCapture:function(a){var b=
this.options;if(this.helper||b.disabled||d(a.target).is(".ui-resizable-handle"))return false;this.handle=this._getHandle(a);if(!this.handle)return false;return true},_mouseStart:function(a){var b=this.options;this.helper=this._createHelper(a);this._cacheHelperProportions();if(d.ui.ddmanager)d.ui.ddmanager.current=this;this._cacheMargins();this.cssPosition=this.helper.css("position");this.scrollParent=this.helper.scrollParent();this.offset=this.positionAbs=this.element.offset();this.offset={top:this.offset.top-
this.margins.top,left:this.offset.left-this.margins.left};d.extend(this.offset,{click:{left:a.pageX-this.offset.left,top:a.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this.position=this._generatePosition(a);this.originalPageX=a.pageX;this.originalPageY=a.pageY;b.cursorAt&&this._adjustOffsetFromHelper(b.cursorAt);b.containment&&this._setContainment();if(this._trigger("start",a)===false){this._clear();return false}this._cacheHelperProportions();
d.ui.ddmanager&&!b.dropBehaviour&&d.ui.ddmanager.prepareOffsets(this,a);this.helper.addClass("ui-draggable-dragging");this._mouseDrag(a,true);return true},_mouseDrag:function(a,b){this.position=this._generatePosition(a);this.positionAbs=this._convertPositionTo("absolute");if(!b){b=this._uiHash();if(this._trigger("drag",a,b)===false){this._mouseUp({});return false}this.position=b.position}if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+"px";if(!this.options.axis||
this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";d.ui.ddmanager&&d.ui.ddmanager.drag(this,a);return false},_mouseStop:function(a){var b=false;if(d.ui.ddmanager&&!this.options.dropBehaviour)b=d.ui.ddmanager.drop(this,a);if(this.dropped){b=this.dropped;this.dropped=false}if(!this.element[0]||!this.element[0].parentNode)return false;if(this.options.revert=="invalid"&&!b||this.options.revert=="valid"&&b||this.options.revert===true||d.isFunction(this.options.revert)&&this.options.revert.call(this.element,
b)){var c=this;d(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){c._trigger("stop",a)!==false&&c._clear()})}else this._trigger("stop",a)!==false&&this._clear();return false},cancel:function(){this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear();return this},_getHandle:function(a){var b=!this.options.handle||!d(this.options.handle,this.element).length?true:false;d(this.options.handle,this.element).find("*").andSelf().each(function(){if(this==
a.target)b=true});return b},_createHelper:function(a){var b=this.options;a=d.isFunction(b.helper)?d(b.helper.apply(this.element[0],[a])):b.helper=="clone"?this.element.clone():this.element;a.parents("body").length||a.appendTo(b.appendTo=="parent"?this.element[0].parentNode:b.appendTo);a[0]!=this.element[0]&&!/(fixed|absolute)/.test(a.css("position"))&&a.css("position","absolute");return a},_adjustOffsetFromHelper:function(a){if(typeof a=="string")a=a.split(" ");if(d.isArray(a))a={left:+a[0],top:+a[1]||
0};if("left"in a)this.offset.click.left=a.left+this.margins.left;if("right"in a)this.offset.click.left=this.helperProportions.width-a.right+this.margins.left;if("top"in a)this.offset.click.top=a.top+this.margins.top;if("bottom"in a)this.offset.click.top=this.helperProportions.height-a.bottom+this.margins.top},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var a=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],
this.offsetParent[0])){a.left+=this.scrollParent.scrollLeft();a.top+=this.scrollParent.scrollTop()}if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&d.browser.msie)a={top:0,left:0};return{top:a.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:a.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var a=this.element.position();return{top:a.top-
(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:a.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var a=this.options;if(a.containment==
"parent")a.containment=this.helper[0].parentNode;if(a.containment=="document"||a.containment=="window")this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,d(a.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(d(a.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(a.containment)&&
a.containment.constructor!=Array){var b=d(a.containment)[0];if(b){a=d(a.containment).offset();var c=d(b).css("overflow")!="hidden";this.containment=[a.left+(parseInt(d(b).css("borderLeftWidth"),10)||0)+(parseInt(d(b).css("paddingLeft"),10)||0)-this.margins.left,a.top+(parseInt(d(b).css("borderTopWidth"),10)||0)+(parseInt(d(b).css("paddingTop"),10)||0)-this.margins.top,a.left+(c?Math.max(b.scrollWidth,b.offsetWidth):b.offsetWidth)-(parseInt(d(b).css("borderLeftWidth"),10)||0)-(parseInt(d(b).css("paddingRight"),
10)||0)-this.helperProportions.width-this.margins.left,a.top+(c?Math.max(b.scrollHeight,b.offsetHeight):b.offsetHeight)-(parseInt(d(b).css("borderTopWidth"),10)||0)-(parseInt(d(b).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}}else if(a.containment.constructor==Array)this.containment=a.containment},_convertPositionTo:function(a,b){if(!b)b=this.position;a=a=="absolute"?1:-1;var c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],
this.offsetParent[0]))?this.offsetParent:this.scrollParent,f=/(html|body)/i.test(c[0].tagName);return{top:b.top+this.offset.relative.top*a+this.offset.parent.top*a-(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():f?0:c.scrollTop())*a),left:b.left+this.offset.relative.left*a+this.offset.parent.left*a-(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():
f?0:c.scrollLeft())*a)}},_generatePosition:function(a){var b=this.options,c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,f=/(html|body)/i.test(c[0].tagName),e=a.pageX,g=a.pageY;if(this.originalPosition){if(this.containment){if(a.pageX-this.offset.click.left<this.containment[0])e=this.containment[0]+this.offset.click.left;if(a.pageY-this.offset.click.top<this.containment[1])g=this.containment[1]+
this.offset.click.top;if(a.pageX-this.offset.click.left>this.containment[2])e=this.containment[2]+this.offset.click.left;if(a.pageY-this.offset.click.top>this.containment[3])g=this.containment[3]+this.offset.click.top}if(b.grid){g=this.originalPageY+Math.round((g-this.originalPageY)/b.grid[1])*b.grid[1];g=this.containment?!(g-this.offset.click.top<this.containment[1]||g-this.offset.click.top>this.containment[3])?g:!(g-this.offset.click.top<this.containment[1])?g-b.grid[1]:g+b.grid[1]:g;e=this.originalPageX+
Math.round((e-this.originalPageX)/b.grid[0])*b.grid[0];e=this.containment?!(e-this.offset.click.left<this.containment[0]||e-this.offset.click.left>this.containment[2])?e:!(e-this.offset.click.left<this.containment[0])?e-b.grid[0]:e+b.grid[0]:e}}return{top:g-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollTop():f?0:c.scrollTop()),left:e-this.offset.click.left-
this.offset.relative.left-this.offset.parent.left+(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():f?0:c.scrollLeft())}},_clear:function(){this.helper.removeClass("ui-draggable-dragging");this.helper[0]!=this.element[0]&&!this.cancelHelperRemoval&&this.helper.remove();this.helper=null;this.cancelHelperRemoval=false},_trigger:function(a,b,c){c=c||this._uiHash();d.ui.plugin.call(this,a,[b,c]);if(a=="drag")this.positionAbs=
this._convertPositionTo("absolute");return d.Widget.prototype._trigger.call(this,a,b,c)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}});d.extend(d.ui.draggable,{version:"1.8.1"});d.ui.plugin.add("draggable","connectToSortable",{start:function(a,b){var c=d(this).data("draggable"),f=c.options,e=d.extend({},b,{item:c.element});c.sortables=[];d(f.connectToSortable).each(function(){var g=d.data(this,"sortable");
if(g&&!g.options.disabled){c.sortables.push({instance:g,shouldRevert:g.options.revert});g._refreshItems();g._trigger("activate",a,e)}})},stop:function(a,b){var c=d(this).data("draggable"),f=d.extend({},b,{item:c.element});d.each(c.sortables,function(){if(this.instance.isOver){this.instance.isOver=0;c.cancelHelperRemoval=true;this.instance.cancelHelperRemoval=false;if(this.shouldRevert)this.instance.options.revert=true;this.instance._mouseStop(a);this.instance.options.helper=this.instance.options._helper;
c.options.helper=="original"&&this.instance.currentItem.css({top:"auto",left:"auto"})}else{this.instance.cancelHelperRemoval=false;this.instance._trigger("deactivate",a,f)}})},drag:function(a,b){var c=d(this).data("draggable"),f=this;d.each(c.sortables,function(){this.instance.positionAbs=c.positionAbs;this.instance.helperProportions=c.helperProportions;this.instance.offset.click=c.offset.click;if(this.instance._intersectsWith(this.instance.containerCache)){if(!this.instance.isOver){this.instance.isOver=
1;this.instance.currentItem=d(f).clone().appendTo(this.instance.element).data("sortable-item",true);this.instance.options._helper=this.instance.options.helper;this.instance.options.helper=function(){return b.helper[0]};a.target=this.instance.currentItem[0];this.instance._mouseCapture(a,true);this.instance._mouseStart(a,true,true);this.instance.offset.click.top=c.offset.click.top;this.instance.offset.click.left=c.offset.click.left;this.instance.offset.parent.left-=c.offset.parent.left-this.instance.offset.parent.left;
this.instance.offset.parent.top-=c.offset.parent.top-this.instance.offset.parent.top;c._trigger("toSortable",a);c.dropped=this.instance.element;c.currentItem=c.element;this.instance.fromOutside=c}this.instance.currentItem&&this.instance._mouseDrag(a)}else if(this.instance.isOver){this.instance.isOver=0;this.instance.cancelHelperRemoval=true;this.instance.options.revert=false;this.instance._trigger("out",a,this.instance._uiHash(this.instance));this.instance._mouseStop(a,true);this.instance.options.helper=
this.instance.options._helper;this.instance.currentItem.remove();this.instance.placeholder&&this.instance.placeholder.remove();c._trigger("fromSortable",a);c.dropped=false}})}});d.ui.plugin.add("draggable","cursor",{start:function(){var a=d("body"),b=d(this).data("draggable").options;if(a.css("cursor"))b._cursor=a.css("cursor");a.css("cursor",b.cursor)},stop:function(){var a=d(this).data("draggable").options;a._cursor&&d("body").css("cursor",a._cursor)}});d.ui.plugin.add("draggable","iframeFix",{start:function(){var a=
d(this).data("draggable").options;d(a.iframeFix===true?"iframe":a.iframeFix).each(function(){d('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1E3}).css(d(this).offset()).appendTo("body")})},stop:function(){d("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)})}});d.ui.plugin.add("draggable","opacity",{start:function(a,b){a=d(b.helper);b=d(this).data("draggable").options;
if(a.css("opacity"))b._opacity=a.css("opacity");a.css("opacity",b.opacity)},stop:function(a,b){a=d(this).data("draggable").options;a._opacity&&d(b.helper).css("opacity",a._opacity)}});d.ui.plugin.add("draggable","scroll",{start:function(){var a=d(this).data("draggable");if(a.scrollParent[0]!=document&&a.scrollParent[0].tagName!="HTML")a.overflowOffset=a.scrollParent.offset()},drag:function(a){var b=d(this).data("draggable"),c=b.options,f=false;if(b.scrollParent[0]!=document&&b.scrollParent[0].tagName!=
"HTML"){if(!c.axis||c.axis!="x")if(b.overflowOffset.top+b.scrollParent[0].offsetHeight-a.pageY<c.scrollSensitivity)b.scrollParent[0].scrollTop=f=b.scrollParent[0].scrollTop+c.scrollSpeed;else if(a.pageY-b.overflowOffset.top<c.scrollSensitivity)b.scrollParent[0].scrollTop=f=b.scrollParent[0].scrollTop-c.scrollSpeed;if(!c.axis||c.axis!="y")if(b.overflowOffset.left+b.scrollParent[0].offsetWidth-a.pageX<c.scrollSensitivity)b.scrollParent[0].scrollLeft=f=b.scrollParent[0].scrollLeft+c.scrollSpeed;else if(a.pageX-
b.overflowOffset.left<c.scrollSensitivity)b.scrollParent[0].scrollLeft=f=b.scrollParent[0].scrollLeft-c.scrollSpeed}else{if(!c.axis||c.axis!="x")if(a.pageY-d(document).scrollTop()<c.scrollSensitivity)f=d(document).scrollTop(d(document).scrollTop()-c.scrollSpeed);else if(d(window).height()-(a.pageY-d(document).scrollTop())<c.scrollSensitivity)f=d(document).scrollTop(d(document).scrollTop()+c.scrollSpeed);if(!c.axis||c.axis!="y")if(a.pageX-d(document).scrollLeft()<c.scrollSensitivity)f=d(document).scrollLeft(d(document).scrollLeft()-
c.scrollSpeed);else if(d(window).width()-(a.pageX-d(document).scrollLeft())<c.scrollSensitivity)f=d(document).scrollLeft(d(document).scrollLeft()+c.scrollSpeed)}f!==false&&d.ui.ddmanager&&!c.dropBehaviour&&d.ui.ddmanager.prepareOffsets(b,a)}});d.ui.plugin.add("draggable","snap",{start:function(){var a=d(this).data("draggable"),b=a.options;a.snapElements=[];d(b.snap.constructor!=String?b.snap.items||":data(draggable)":b.snap).each(function(){var c=d(this),f=c.offset();this!=a.element[0]&&a.snapElements.push({item:this,
width:c.outerWidth(),height:c.outerHeight(),top:f.top,left:f.left})})},drag:function(a,b){for(var c=d(this).data("draggable"),f=c.options,e=f.snapTolerance,g=b.offset.left,n=g+c.helperProportions.width,m=b.offset.top,o=m+c.helperProportions.height,h=c.snapElements.length-1;h>=0;h--){var i=c.snapElements[h].left,k=i+c.snapElements[h].width,j=c.snapElements[h].top,l=j+c.snapElements[h].height;if(i-e<g&&g<k+e&&j-e<m&&m<l+e||i-e<g&&g<k+e&&j-e<o&&o<l+e||i-e<n&&n<k+e&&j-e<m&&m<l+e||i-e<n&&n<k+e&&j-e<o&&
o<l+e){if(f.snapMode!="inner"){var p=Math.abs(j-o)<=e,q=Math.abs(l-m)<=e,r=Math.abs(i-n)<=e,s=Math.abs(k-g)<=e;if(p)b.position.top=c._convertPositionTo("relative",{top:j-c.helperProportions.height,left:0}).top-c.margins.top;if(q)b.position.top=c._convertPositionTo("relative",{top:l,left:0}).top-c.margins.top;if(r)b.position.left=c._convertPositionTo("relative",{top:0,left:i-c.helperProportions.width}).left-c.margins.left;if(s)b.position.left=c._convertPositionTo("relative",{top:0,left:k}).left-c.margins.left}var t=
p||q||r||s;if(f.snapMode!="outer"){p=Math.abs(j-m)<=e;q=Math.abs(l-o)<=e;r=Math.abs(i-g)<=e;s=Math.abs(k-n)<=e;if(p)b.position.top=c._convertPositionTo("relative",{top:j,left:0}).top-c.margins.top;if(q)b.position.top=c._convertPositionTo("relative",{top:l-c.helperProportions.height,left:0}).top-c.margins.top;if(r)b.position.left=c._convertPositionTo("relative",{top:0,left:i}).left-c.margins.left;if(s)b.position.left=c._convertPositionTo("relative",{top:0,left:k-c.helperProportions.width}).left-c.margins.left}if(!c.snapElements[h].snapping&&
(p||q||r||s||t))c.options.snap.snap&&c.options.snap.snap.call(c.element,a,d.extend(c._uiHash(),{snapItem:c.snapElements[h].item}));c.snapElements[h].snapping=p||q||r||s||t}else{c.snapElements[h].snapping&&c.options.snap.release&&c.options.snap.release.call(c.element,a,d.extend(c._uiHash(),{snapItem:c.snapElements[h].item}));c.snapElements[h].snapping=false}}}});d.ui.plugin.add("draggable","stack",{start:function(){var a=d(this).data("draggable").options;a=d.makeArray(d(a.stack)).sort(function(c,f){return(parseInt(d(c).css("zIndex"),
10)||0)-(parseInt(d(f).css("zIndex"),10)||0)});if(a.length){var b=parseInt(a[0].style.zIndex)||0;d(a).each(function(c){this.style.zIndex=b+c});this[0].style.zIndex=b+a.length}}});d.ui.plugin.add("draggable","zIndex",{start:function(a,b){a=d(b.helper);b=d(this).data("draggable").options;if(a.css("zIndex"))b._zIndex=a.css("zIndex");a.css("zIndex",b.zIndex)},stop:function(a,b){a=d(this).data("draggable").options;a._zIndex&&d(b.helper).css("zIndex",a._zIndex)}})})(jQuery);
(function(d){d.widget("ui.droppable",{widgetEventPrefix:"drop",options:{accept:"*",activeClass:false,addClasses:true,greedy:false,hoverClass:false,scope:"default",tolerance:"intersect"},_create:function(){var a=this.options,b=a.accept;this.isover=0;this.isout=1;this.accept=d.isFunction(b)?b:function(c){return c.is(b)};this.proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight};d.ui.ddmanager.droppables[a.scope]=d.ui.ddmanager.droppables[a.scope]||[];d.ui.ddmanager.droppables[a.scope].push(this);
a.addClasses&&this.element.addClass("ui-droppable")},destroy:function(){for(var a=d.ui.ddmanager.droppables[this.options.scope],b=0;b<a.length;b++)a[b]==this&&a.splice(b,1);this.element.removeClass("ui-droppable ui-droppable-disabled").removeData("droppable").unbind(".droppable");return this},_setOption:function(a,b){if(a=="accept")this.accept=d.isFunction(b)?b:function(c){return c.is(b)};d.Widget.prototype._setOption.apply(this,arguments)},_activate:function(a){var b=d.ui.ddmanager.current;this.options.activeClass&&
this.element.addClass(this.options.activeClass);b&&this._trigger("activate",a,this.ui(b))},_deactivate:function(a){var b=d.ui.ddmanager.current;this.options.activeClass&&this.element.removeClass(this.options.activeClass);b&&this._trigger("deactivate",a,this.ui(b))},_over:function(a){var b=d.ui.ddmanager.current;if(!(!b||(b.currentItem||b.element)[0]==this.element[0]))if(this.accept.call(this.element[0],b.currentItem||b.element)){this.options.hoverClass&&this.element.addClass(this.options.hoverClass);
this._trigger("over",a,this.ui(b))}},_out:function(a){var b=d.ui.ddmanager.current;if(!(!b||(b.currentItem||b.element)[0]==this.element[0]))if(this.accept.call(this.element[0],b.currentItem||b.element)){this.options.hoverClass&&this.element.removeClass(this.options.hoverClass);this._trigger("out",a,this.ui(b))}},_drop:function(a,b){var c=b||d.ui.ddmanager.current;if(!c||(c.currentItem||c.element)[0]==this.element[0])return false;var e=false;this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function(){var g=
d.data(this,"droppable");if(g.options.greedy&&!g.options.disabled&&g.options.scope==c.options.scope&&g.accept.call(g.element[0],c.currentItem||c.element)&&d.ui.intersect(c,d.extend(g,{offset:g.element.offset()}),g.options.tolerance)){e=true;return false}});if(e)return false;if(this.accept.call(this.element[0],c.currentItem||c.element)){this.options.activeClass&&this.element.removeClass(this.options.activeClass);this.options.hoverClass&&this.element.removeClass(this.options.hoverClass);this._trigger("drop",
a,this.ui(c));return this.element}return false},ui:function(a){return{draggable:a.currentItem||a.element,helper:a.helper,position:a.position,offset:a.positionAbs}}});d.extend(d.ui.droppable,{version:"1.8.1"});d.ui.intersect=function(a,b,c){if(!b.offset)return false;var e=(a.positionAbs||a.position.absolute).left,g=e+a.helperProportions.width,f=(a.positionAbs||a.position.absolute).top,h=f+a.helperProportions.height,i=b.offset.left,k=i+b.proportions.width,j=b.offset.top,l=j+b.proportions.height;
switch(c){case "fit":return i<e&&g<k&&j<f&&h<l;case "intersect":return i<e+a.helperProportions.width/2&&g-a.helperProportions.width/2<k&&j<f+a.helperProportions.height/2&&h-a.helperProportions.height/2<l;case "pointer":return d.ui.isOver((a.positionAbs||a.position.absolute).top+(a.clickOffset||a.offset.click).top,(a.positionAbs||a.position.absolute).left+(a.clickOffset||a.offset.click).left,j,i,b.proportions.height,b.proportions.width);case "touch":return(f>=j&&f<=l||h>=j&&h<=l||f<j&&h>l)&&(e>=i&&
e<=k||g>=i&&g<=k||e<i&&g>k);default:return false}};d.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(a,b){var c=d.ui.ddmanager.droppables[a.options.scope]||[],e=b?b.type:null,g=(a.currentItem||a.element).find(":data(droppable)").andSelf(),f=0;a:for(;f<c.length;f++)if(!(c[f].options.disabled||a&&!c[f].accept.call(c[f].element[0],a.currentItem||a.element))){for(var h=0;h<g.length;h++)if(g[h]==c[f].element[0]){c[f].proportions.height=0;continue a}c[f].visible=c[f].element.css("display")!=
"none";if(c[f].visible){c[f].offset=c[f].element.offset();c[f].proportions={width:c[f].element[0].offsetWidth,height:c[f].element[0].offsetHeight};e=="mousedown"&&c[f]._activate.call(c[f],b)}}},drop:function(a,b){var c=false;d.each(d.ui.ddmanager.droppables[a.options.scope]||[],function(){if(this.options){if(!this.options.disabled&&this.visible&&d.ui.intersect(a,this,this.options.tolerance))c=c||this._drop.call(this,b);if(!this.options.disabled&&this.visible&&this.accept.call(this.element[0],a.currentItem||
a.element)){this.isout=1;this.isover=0;this._deactivate.call(this,b)}}});return c},drag:function(a,b){a.options.refreshPositions&&d.ui.ddmanager.prepareOffsets(a,b);d.each(d.ui.ddmanager.droppables[a.options.scope]||[],function(){if(!(this.options.disabled||this.greedyChild||!this.visible)){var c=d.ui.intersect(a,this,this.options.tolerance);if(c=!c&&this.isover==1?"isout":c&&this.isover==0?"isover":null){var e;if(this.options.greedy){var g=this.element.parents(":data(droppable):eq(0)");if(g.length){e=
d.data(g[0],"droppable");e.greedyChild=c=="isover"?1:0}}if(e&&c=="isover"){e.isover=0;e.isout=1;e._out.call(e,b)}this[c]=1;this[c=="isout"?"isover":"isout"]=0;this[c=="isover"?"_over":"_out"].call(this,b);if(e&&c=="isout"){e.isout=0;e.isover=1;e._over.call(e,b)}}}})}}})(jQuery);
(function(d){d.widget("ui.resizable",d.ui.mouse,{widgetEventPrefix:"resize",options:{alsoResize:false,animate:false,animateDuration:"slow",animateEasing:"swing",aspectRatio:false,autoHide:false,containment:false,ghost:false,grid:false,handles:"e,s,se",helper:false,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:1E3},_create:function(){var b=this,a=this.options;this.element.addClass("ui-resizable");d.extend(this,{_aspectRatio:!!a.aspectRatio,aspectRatio:a.aspectRatio,originalElement:this.element,
_proportionallyResizeElements:[],_helper:a.helper||a.ghost||a.animate?a.helper||"ui-resizable-helper":null});if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)){/relative/.test(this.element.css("position"))&&d.browser.opera&&this.element.css({position:"relative",top:"auto",left:"auto"});this.element.wrap(d('<div class="ui-wrapper" style="overflow: hidden;"></div>').css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),
top:this.element.css("top"),left:this.element.css("left")}));this.element=this.element.parent().data("resizable",this.element.data("resizable"));this.elementIsWrapper=true;this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")});this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0});this.originalResizeStyle=
this.originalElement.css("resize");this.originalElement.css("resize","none");this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"}));this.originalElement.css({margin:this.originalElement.css("margin")});this._proportionallyResize()}this.handles=a.handles||(!d(".ui-resizable-handle",this.element).length?"e,s,se":{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",
nw:".ui-resizable-nw"});if(this.handles.constructor==String){if(this.handles=="all")this.handles="n,e,s,w,se,sw,ne,nw";var c=this.handles.split(",");this.handles={};for(var e=0;e<c.length;e++){var g=d.trim(c[e]),f=d('<div class="ui-resizable-handle '+("ui-resizable-"+g)+'"></div>');/sw|se|ne|nw/.test(g)&&f.css({zIndex:++a.zIndex});"se"==g&&f.addClass("ui-icon ui-icon-gripsmall-diagonal-se");this.handles[g]=".ui-resizable-"+g;this.element.append(f)}}this._renderAxis=function(h){h=h||this.element;for(var i in this.handles){if(this.handles[i].constructor==
String)this.handles[i]=d(this.handles[i],this.element).show();if(this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)){var j=d(this.handles[i],this.element),l=0;l=/sw|ne|nw|se|n|s/.test(i)?j.outerHeight():j.outerWidth();j=["padding",/ne|nw|n/.test(i)?"Top":/se|sw|s/.test(i)?"Bottom":/^e$/.test(i)?"Right":"Left"].join("");h.css(j,l);this._proportionallyResize()}d(this.handles[i])}};this._renderAxis(this.element);this._handles=d(".ui-resizable-handle",this.element).disableSelection();
this._handles.mouseover(function(){if(!b.resizing){if(this.className)var h=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);b.axis=h&&h[1]?h[1]:"se"}});if(a.autoHide){this._handles.hide();d(this.element).addClass("ui-resizable-autohide").hover(function(){d(this).removeClass("ui-resizable-autohide");b._handles.show()},function(){if(!b.resizing){d(this).addClass("ui-resizable-autohide");b._handles.hide()}})}this._mouseInit()},destroy:function(){this._mouseDestroy();var b=function(c){d(c).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};
if(this.elementIsWrapper){b(this.element);var a=this.element;a.after(this.originalElement.css({position:a.css("position"),width:a.outerWidth(),height:a.outerHeight(),top:a.css("top"),left:a.css("left")})).remove()}this.originalElement.css("resize",this.originalResizeStyle);b(this.originalElement);return this},_mouseCapture:function(b){var a=false;for(var c in this.handles)if(d(this.handles[c])[0]==b.target)a=true;return!this.options.disabled&&a},_mouseStart:function(b){var a=this.options,c=this.element.position(),
e=this.element;this.resizing=true;this.documentScroll={top:d(document).scrollTop(),left:d(document).scrollLeft()};if(e.is(".ui-draggable")||/absolute/.test(e.css("position")))e.css({position:"absolute",top:c.top,left:c.left});d.browser.opera&&/relative/.test(e.css("position"))&&e.css({position:"relative",top:"auto",left:"auto"});this._renderProxy();c=m(this.helper.css("left"));var g=m(this.helper.css("top"));if(a.containment){c+=d(a.containment).scrollLeft()||0;g+=d(a.containment).scrollTop()||0}this.offset=
this.helper.offset();this.position={left:c,top:g};this.size=this._helper?{width:e.outerWidth(),height:e.outerHeight()}:{width:e.width(),height:e.height()};this.originalSize=this._helper?{width:e.outerWidth(),height:e.outerHeight()}:{width:e.width(),height:e.height()};this.originalPosition={left:c,top:g};this.sizeDiff={width:e.outerWidth()-e.width(),height:e.outerHeight()-e.height()};this.originalMousePosition={left:b.pageX,top:b.pageY};this.aspectRatio=typeof a.aspectRatio=="number"?a.aspectRatio:
this.originalSize.width/this.originalSize.height||1;a=d(".ui-resizable-"+this.axis).css("cursor");d("body").css("cursor",a=="auto"?this.axis+"-resize":a);e.addClass("ui-resizable-resizing");this._propagate("start",b);return true},_mouseDrag:function(b){var a=this.helper,c=this.originalMousePosition,e=this._change[this.axis];if(!e)return false;c=e.apply(this,[b,b.pageX-c.left||0,b.pageY-c.top||0]);if(this._aspectRatio||b.shiftKey)c=this._updateRatio(c,b);c=this._respectSize(c,b);this._propagate("resize",
b);a.css({top:this.position.top+"px",left:this.position.left+"px",width:this.size.width+"px",height:this.size.height+"px"});!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize();this._updateCache(c);this._trigger("resize",b,this.ui());return false},_mouseStop:function(b){this.resizing=false;var a=this.options,c=this;if(this._helper){var e=this._proportionallyResizeElements,g=e.length&&/textarea/i.test(e[0].nodeName);e=g&&d.ui.hasScroll(e[0],"left")?0:c.sizeDiff.height;
g={width:c.size.width-(g?0:c.sizeDiff.width),height:c.size.height-e};e=parseInt(c.element.css("left"),10)+(c.position.left-c.originalPosition.left)||null;var f=parseInt(c.element.css("top"),10)+(c.position.top-c.originalPosition.top)||null;a.animate||this.element.css(d.extend(g,{top:f,left:e}));c.helper.height(c.size.height);c.helper.width(c.size.width);this._helper&&!a.animate&&this._proportionallyResize()}d("body").css("cursor","auto");this.element.removeClass("ui-resizable-resizing");this._propagate("stop",
b);this._helper&&this.helper.remove();return false},_updateCache:function(b){this.offset=this.helper.offset();if(k(b.left))this.position.left=b.left;if(k(b.top))this.position.top=b.top;if(k(b.height))this.size.height=b.height;if(k(b.width))this.size.width=b.width},_updateRatio:function(b){var a=this.position,c=this.size,e=this.axis;if(b.height)b.width=c.height*this.aspectRatio;else if(b.width)b.height=c.width/this.aspectRatio;if(e=="sw"){b.left=a.left+(c.width-b.width);b.top=null}if(e=="nw"){b.top=
a.top+(c.height-b.height);b.left=a.left+(c.width-b.width)}return b},_respectSize:function(b){var a=this.options,c=this.axis,e=k(b.width)&&a.maxWidth&&a.maxWidth<b.width,g=k(b.height)&&a.maxHeight&&a.maxHeight<b.height,f=k(b.width)&&a.minWidth&&a.minWidth>b.width,h=k(b.height)&&a.minHeight&&a.minHeight>b.height;if(f)b.width=a.minWidth;if(h)b.height=a.minHeight;if(e)b.width=a.maxWidth;if(g)b.height=a.maxHeight;var i=this.originalPosition.left+this.originalSize.width,j=this.position.top+this.size.height,
l=/sw|nw|w/.test(c);c=/nw|ne|n/.test(c);if(f&&l)b.left=i-a.minWidth;if(e&&l)b.left=i-a.maxWidth;if(h&&c)b.top=j-a.minHeight;if(g&&c)b.top=j-a.maxHeight;if((a=!b.width&&!b.height)&&!b.left&&b.top)b.top=null;else if(a&&!b.top&&b.left)b.left=null;return b},_proportionallyResize:function(){if(this._proportionallyResizeElements.length)for(var b=this.helper||this.element,a=0;a<this._proportionallyResizeElements.length;a++){var c=this._proportionallyResizeElements[a];if(!this.borderDif){var e=[c.css("borderTopWidth"),
c.css("borderRightWidth"),c.css("borderBottomWidth"),c.css("borderLeftWidth")],g=[c.css("paddingTop"),c.css("paddingRight"),c.css("paddingBottom"),c.css("paddingLeft")];this.borderDif=d.map(e,function(f,h){f=parseInt(f,10)||0;h=parseInt(g[h],10)||0;return f+h})}d.browser.msie&&(d(b).is(":hidden")||d(b).parents(":hidden").length)||c.css({height:b.height()-this.borderDif[0]-this.borderDif[2]||0,width:b.width()-this.borderDif[1]-this.borderDif[3]||0})}},_renderProxy:function(){var b=this.options;this.elementOffset=
this.element.offset();if(this._helper){this.helper=this.helper||d('<div style="overflow:hidden;"></div>');var a=d.browser.msie&&d.browser.version<7,c=a?1:0;a=a?2:-1;this.helper.addClass(this._helper).css({width:this.element.outerWidth()+a,height:this.element.outerHeight()+a,position:"absolute",left:this.elementOffset.left-c+"px",top:this.elementOffset.top-c+"px",zIndex:++b.zIndex});this.helper.appendTo("body").disableSelection()}else this.helper=this.element},_change:{e:function(b,a){return{width:this.originalSize.width+
a}},w:function(b,a){return{left:this.originalPosition.left+a,width:this.originalSize.width-a}},n:function(b,a,c){return{top:this.originalPosition.top+c,height:this.originalSize.height-c}},s:function(b,a,c){return{height:this.originalSize.height+c}},se:function(b,a,c){return d.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[b,a,c]))},sw:function(b,a,c){return d.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[b,a,c]))},ne:function(b,a,c){return d.extend(this._change.n.apply(this,
arguments),this._change.e.apply(this,[b,a,c]))},nw:function(b,a,c){return d.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[b,a,c]))}},_propagate:function(b,a){d.ui.plugin.call(this,b,[a,this.ui()]);b!="resize"&&this._trigger(b,a,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}});d.extend(d.ui.resizable,
{version:"1.8.1"});d.ui.plugin.add("resizable","alsoResize",{start:function(){var b=d(this).data("resizable").options,a=function(c){d(c).each(function(){d(this).data("resizable-alsoresize",{width:parseInt(d(this).width(),10),height:parseInt(d(this).height(),10),left:parseInt(d(this).css("left"),10),top:parseInt(d(this).css("top"),10)})})};if(typeof b.alsoResize=="object"&&!b.alsoResize.parentNode)if(b.alsoResize.length){b.alsoResize=b.alsoResize[0];a(b.alsoResize)}else d.each(b.alsoResize,function(c){a(c)});
else a(b.alsoResize)},resize:function(){var b=d(this).data("resizable"),a=b.options,c=b.originalSize,e=b.originalPosition,g={height:b.size.height-c.height||0,width:b.size.width-c.width||0,top:b.position.top-e.top||0,left:b.position.left-e.left||0},f=function(h,i){d(h).each(function(){var j=d(this),l=d(this).data("resizable-alsoresize"),p={};d.each((i&&i.length?i:["width","height","top","left"])||["width","height","top","left"],function(n,o){if((n=(l[o]||0)+(g[o]||0))&&n>=0)p[o]=n||null});if(/relative/.test(j.css("position"))&&
d.browser.opera){b._revertToRelativePosition=true;j.css({position:"absolute",top:"auto",left:"auto"})}j.css(p)})};typeof a.alsoResize=="object"&&!a.alsoResize.nodeType?d.each(a.alsoResize,function(h,i){f(h,i)}):f(a.alsoResize)},stop:function(){var b=d(this).data("resizable");if(b._revertToRelativePosition&&d.browser.opera){b._revertToRelativePosition=false;el.css({position:"relative"})}d(this).removeData("resizable-alsoresize-start")}});d.ui.plugin.add("resizable","animate",{stop:function(b){var a=
d(this).data("resizable"),c=a.options,e=a._proportionallyResizeElements,g=e.length&&/textarea/i.test(e[0].nodeName),f=g&&d.ui.hasScroll(e[0],"left")?0:a.sizeDiff.height;g={width:a.size.width-(g?0:a.sizeDiff.width),height:a.size.height-f};f=parseInt(a.element.css("left"),10)+(a.position.left-a.originalPosition.left)||null;var h=parseInt(a.element.css("top"),10)+(a.position.top-a.originalPosition.top)||null;a.element.animate(d.extend(g,h&&f?{top:h,left:f}:{}),{duration:c.animateDuration,easing:c.animateEasing,
step:function(){var i={width:parseInt(a.element.css("width"),10),height:parseInt(a.element.css("height"),10),top:parseInt(a.element.css("top"),10),left:parseInt(a.element.css("left"),10)};e&&e.length&&d(e[0]).css({width:i.width,height:i.height});a._updateCache(i);a._propagate("resize",b)}})}});d.ui.plugin.add("resizable","containment",{start:function(){var b=d(this).data("resizable"),a=b.element,c=b.options.containment;if(a=c instanceof d?c.get(0):/parent/.test(c)?a.parent().get(0):c){b.containerElement=
d(a);if(/document/.test(c)||c==document){b.containerOffset={left:0,top:0};b.containerPosition={left:0,top:0};b.parentData={element:d(document),left:0,top:0,width:d(document).width(),height:d(document).height()||document.body.parentNode.scrollHeight}}else{var e=d(a),g=[];d(["Top","Right","Left","Bottom"]).each(function(i,j){g[i]=m(e.css("padding"+j))});b.containerOffset=e.offset();b.containerPosition=e.position();b.containerSize={height:e.innerHeight()-g[3],width:e.innerWidth()-g[1]};c=b.containerOffset;
var f=b.containerSize.height,h=b.containerSize.width;h=d.ui.hasScroll(a,"left")?a.scrollWidth:h;f=d.ui.hasScroll(a)?a.scrollHeight:f;b.parentData={element:a,left:c.left,top:c.top,width:h,height:f}}}},resize:function(b){var a=d(this).data("resizable"),c=a.options,e=a.containerOffset,g=a.position;b=a._aspectRatio||b.shiftKey;var f={top:0,left:0},h=a.containerElement;if(h[0]!=document&&/static/.test(h.css("position")))f=e;if(g.left<(a._helper?e.left:0)){a.size.width+=a._helper?a.position.left-e.left:
a.position.left-f.left;if(b)a.size.height=a.size.width/c.aspectRatio;a.position.left=c.helper?e.left:0}if(g.top<(a._helper?e.top:0)){a.size.height+=a._helper?a.position.top-e.top:a.position.top;if(b)a.size.width=a.size.height*c.aspectRatio;a.position.top=a._helper?e.top:0}a.offset.left=a.parentData.left+a.position.left;a.offset.top=a.parentData.top+a.position.top;c=Math.abs((a._helper?a.offset.left-f.left:a.offset.left-f.left)+a.sizeDiff.width);e=Math.abs((a._helper?a.offset.top-f.top:a.offset.top-
e.top)+a.sizeDiff.height);g=a.containerElement.get(0)==a.element.parent().get(0);f=/relative|absolute/.test(a.containerElement.css("position"));if(g&&f)c-=a.parentData.left;if(c+a.size.width>=a.parentData.width){a.size.width=a.parentData.width-c;if(b)a.size.height=a.size.width/a.aspectRatio}if(e+a.size.height>=a.parentData.height){a.size.height=a.parentData.height-e;if(b)a.size.width=a.size.height*a.aspectRatio}},stop:function(){var b=d(this).data("resizable"),a=b.options,c=b.containerOffset,e=b.containerPosition,
g=b.containerElement,f=d(b.helper),h=f.offset(),i=f.outerWidth()-b.sizeDiff.width;f=f.outerHeight()-b.sizeDiff.height;b._helper&&!a.animate&&/relative/.test(g.css("position"))&&d(this).css({left:h.left-e.left-c.left,width:i,height:f});b._helper&&!a.animate&&/static/.test(g.css("position"))&&d(this).css({left:h.left-e.left-c.left,width:i,height:f})}});d.ui.plugin.add("resizable","ghost",{start:function(){var b=d(this).data("resizable"),a=b.options,c=b.size;b.ghost=b.originalElement.clone();b.ghost.css({opacity:0.25,
display:"block",position:"relative",height:c.height,width:c.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass(typeof a.ghost=="string"?a.ghost:"");b.ghost.appendTo(b.helper)},resize:function(){var b=d(this).data("resizable");b.ghost&&b.ghost.css({position:"relative",height:b.size.height,width:b.size.width})},stop:function(){var b=d(this).data("resizable");b.ghost&&b.helper&&b.helper.get(0).removeChild(b.ghost.get(0))}});d.ui.plugin.add("resizable","grid",{resize:function(){var b=
d(this).data("resizable"),a=b.options,c=b.size,e=b.originalSize,g=b.originalPosition,f=b.axis;a.grid=typeof a.grid=="number"?[a.grid,a.grid]:a.grid;var h=Math.round((c.width-e.width)/(a.grid[0]||1))*(a.grid[0]||1);a=Math.round((c.height-e.height)/(a.grid[1]||1))*(a.grid[1]||1);if(/^(se|s|e)$/.test(f)){b.size.width=e.width+h;b.size.height=e.height+a}else if(/^(ne)$/.test(f)){b.size.width=e.width+h;b.size.height=e.height+a;b.position.top=g.top-a}else{if(/^(sw)$/.test(f)){b.size.width=e.width+h;b.size.height=
e.height+a}else{b.size.width=e.width+h;b.size.height=e.height+a;b.position.top=g.top-a}b.position.left=g.left-h}}});var m=function(b){return parseInt(b,10)||0},k=function(b){return!isNaN(parseInt(b,10))}})(jQuery);
(function(e){e.widget("ui.selectable",e.ui.mouse,{options:{appendTo:"body",autoRefresh:true,distance:0,filter:"*",tolerance:"touch"},_create:function(){var d=this;this.element.addClass("ui-selectable");this.dragged=false;var f;this.refresh=function(){f=e(d.options.filter,d.element[0]);f.each(function(){var c=e(this),b=c.offset();e.data(this,"selectable-item",{element:this,$element:c,left:b.left,top:b.top,right:b.left+c.outerWidth(),bottom:b.top+c.outerHeight(),startselected:false,selected:c.hasClass("ui-selected"),
selecting:c.hasClass("ui-selecting"),unselecting:c.hasClass("ui-unselecting")})})};this.refresh();this.selectees=f.addClass("ui-selectee");this._mouseInit();this.helper=e(document.createElement("div")).css({border:"1px dotted black"}).addClass("ui-selectable-helper")},destroy:function(){this.selectees.removeClass("ui-selectee").removeData("selectable-item");this.element.removeClass("ui-selectable ui-selectable-disabled").removeData("selectable").unbind(".selectable");this._mouseDestroy();return this},
_mouseStart:function(d){var f=this;this.opos=[d.pageX,d.pageY];if(!this.options.disabled){var c=this.options;this.selectees=e(c.filter,this.element[0]);this._trigger("start",d);e(c.appendTo).append(this.helper);this.helper.css({"z-index":100,position:"absolute",left:d.clientX,top:d.clientY,width:0,height:0});c.autoRefresh&&this.refresh();this.selectees.filter(".ui-selected").each(function(){var b=e.data(this,"selectable-item");b.startselected=true;if(!d.metaKey){b.$element.removeClass("ui-selected");
b.selected=false;b.$element.addClass("ui-unselecting");b.unselecting=true;f._trigger("unselecting",d,{unselecting:b.element})}});e(d.target).parents().andSelf().each(function(){var b=e.data(this,"selectable-item");if(b){b.$element.removeClass("ui-unselecting").addClass("ui-selecting");b.unselecting=false;b.selecting=true;b.selected=true;f._trigger("selecting",d,{selecting:b.element});return false}})}},_mouseDrag:function(d){var f=this;this.dragged=true;if(!this.options.disabled){var c=this.options,
b=this.opos[0],g=this.opos[1],h=d.pageX,i=d.pageY;if(b>h){var j=h;h=b;b=j}if(g>i){j=i;i=g;g=j}this.helper.css({left:b,top:g,width:h-b,height:i-g});this.selectees.each(function(){var a=e.data(this,"selectable-item");if(!(!a||a.element==f.element[0])){var k=false;if(c.tolerance=="touch")k=!(a.left>h||a.right<b||a.top>i||a.bottom<g);else if(c.tolerance=="fit")k=a.left>b&&a.right<h&&a.top>g&&a.bottom<i;if(k){if(a.selected){a.$element.removeClass("ui-selected");a.selected=false}if(a.unselecting){a.$element.removeClass("ui-unselecting");
a.unselecting=false}if(!a.selecting){a.$element.addClass("ui-selecting");a.selecting=true;f._trigger("selecting",d,{selecting:a.element})}}else{if(a.selecting)if(d.metaKey&&a.startselected){a.$element.removeClass("ui-selecting");a.selecting=false;a.$element.addClass("ui-selected");a.selected=true}else{a.$element.removeClass("ui-selecting");a.selecting=false;if(a.startselected){a.$element.addClass("ui-unselecting");a.unselecting=true}f._trigger("unselecting",d,{unselecting:a.element})}if(a.selected)if(!d.metaKey&&
!a.startselected){a.$element.removeClass("ui-selected");a.selected=false;a.$element.addClass("ui-unselecting");a.unselecting=true;f._trigger("unselecting",d,{unselecting:a.element})}}}});return false}},_mouseStop:function(d){var f=this;this.dragged=false;e(".ui-unselecting",this.element[0]).each(function(){var c=e.data(this,"selectable-item");c.$element.removeClass("ui-unselecting");c.unselecting=false;c.startselected=false;f._trigger("unselected",d,{unselected:c.element})});e(".ui-selecting",this.element[0]).each(function(){var c=
e.data(this,"selectable-item");c.$element.removeClass("ui-selecting").addClass("ui-selected");c.selecting=false;c.selected=true;c.startselected=true;f._trigger("selected",d,{selected:c.element})});this._trigger("stop",d);this.helper.remove();return false}});e.extend(e.ui.selectable,{version:"1.8.1"})})(jQuery);
(function(d){d.widget("ui.sortable",d.ui.mouse,{widgetEventPrefix:"sort",options:{appendTo:"parent",axis:false,connectWith:false,containment:false,cursor:"auto",cursorAt:false,dropOnEmpty:true,forcePlaceholderSize:false,forceHelperSize:false,grid:false,handle:false,helper:"original",items:"> *",opacity:false,placeholder:false,revert:false,scroll:true,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1E3},_create:function(){this.containerCache={};this.element.addClass("ui-sortable");
this.refresh();this.floating=this.items.length?/left|right/.test(this.items[0].item.css("float")):false;this.offset=this.element.offset();this._mouseInit()},destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled").removeData("sortable").unbind(".sortable");this._mouseDestroy();for(var a=this.items.length-1;a>=0;a--)this.items[a].item.removeData("sortable-item");return this},_setOption:function(a,b){if(a==="disabled"){this.options[a]=b;this.widget()[b?"addClass":"removeClass"]("ui-sortable-disabled")}else d.Widget.prototype._setOption.apply(self,
arguments)},_mouseCapture:function(a,b){if(this.reverting)return false;if(this.options.disabled||this.options.type=="static")return false;this._refreshItems(a);var c=null,e=this;d(a.target).parents().each(function(){if(d.data(this,"sortable-item")==e){c=d(this);return false}});if(d.data(a.target,"sortable-item")==e)c=d(a.target);if(!c)return false;if(this.options.handle&&!b){var f=false;d(this.options.handle,c).find("*").andSelf().each(function(){if(this==a.target)f=true});if(!f)return false}this.currentItem=
c;this._removeCurrentsFromItems();return true},_mouseStart:function(a,b,c){b=this.options;var e=this;this.currentContainer=this;this.refreshPositions();this.helper=this._createHelper(a);this._cacheHelperProportions();this._cacheMargins();this.scrollParent=this.helper.scrollParent();this.offset=this.currentItem.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};this.helper.css("position","absolute");this.cssPosition=this.helper.css("position");d.extend(this.offset,
{click:{left:a.pageX-this.offset.left,top:a.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this._generatePosition(a);this.originalPageX=a.pageX;this.originalPageY=a.pageY;b.cursorAt&&this._adjustOffsetFromHelper(b.cursorAt);this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]};this.helper[0]!=this.currentItem[0]&&this.currentItem.hide();this._createPlaceholder();b.containment&&this._setContainment();
if(b.cursor){if(d("body").css("cursor"))this._storedCursor=d("body").css("cursor");d("body").css("cursor",b.cursor)}if(b.opacity){if(this.helper.css("opacity"))this._storedOpacity=this.helper.css("opacity");this.helper.css("opacity",b.opacity)}if(b.zIndex){if(this.helper.css("zIndex"))this._storedZIndex=this.helper.css("zIndex");this.helper.css("zIndex",b.zIndex)}if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML")this.overflowOffset=this.scrollParent.offset();this._trigger("start",
a,this._uiHash());this._preserveHelperProportions||this._cacheHelperProportions();if(!c)for(c=this.containers.length-1;c>=0;c--)this.containers[c]._trigger("activate",a,e._uiHash(this));if(d.ui.ddmanager)d.ui.ddmanager.current=this;d.ui.ddmanager&&!b.dropBehaviour&&d.ui.ddmanager.prepareOffsets(this,a);this.dragging=true;this.helper.addClass("ui-sortable-helper");this._mouseDrag(a);return true},_mouseDrag:function(a){this.position=this._generatePosition(a);this.positionAbs=this._convertPositionTo("absolute");
if(!this.lastPositionAbs)this.lastPositionAbs=this.positionAbs;if(this.options.scroll){var b=this.options,c=false;if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"){if(this.overflowOffset.top+this.scrollParent[0].offsetHeight-a.pageY<b.scrollSensitivity)this.scrollParent[0].scrollTop=c=this.scrollParent[0].scrollTop+b.scrollSpeed;else if(a.pageY-this.overflowOffset.top<b.scrollSensitivity)this.scrollParent[0].scrollTop=c=this.scrollParent[0].scrollTop-b.scrollSpeed;if(this.overflowOffset.left+
this.scrollParent[0].offsetWidth-a.pageX<b.scrollSensitivity)this.scrollParent[0].scrollLeft=c=this.scrollParent[0].scrollLeft+b.scrollSpeed;else if(a.pageX-this.overflowOffset.left<b.scrollSensitivity)this.scrollParent[0].scrollLeft=c=this.scrollParent[0].scrollLeft-b.scrollSpeed}else{if(a.pageY-d(document).scrollTop()<b.scrollSensitivity)c=d(document).scrollTop(d(document).scrollTop()-b.scrollSpeed);else if(d(window).height()-(a.pageY-d(document).scrollTop())<b.scrollSensitivity)c=d(document).scrollTop(d(document).scrollTop()+
b.scrollSpeed);if(a.pageX-d(document).scrollLeft()<b.scrollSensitivity)c=d(document).scrollLeft(d(document).scrollLeft()-b.scrollSpeed);else if(d(window).width()-(a.pageX-d(document).scrollLeft())<b.scrollSensitivity)c=d(document).scrollLeft(d(document).scrollLeft()+b.scrollSpeed)}c!==false&&d.ui.ddmanager&&!b.dropBehaviour&&d.ui.ddmanager.prepareOffsets(this,a)}this.positionAbs=this._convertPositionTo("absolute");if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+
"px";if(!this.options.axis||this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";for(b=this.items.length-1;b>=0;b--){c=this.items[b];var e=c.item[0],f=this._intersectsWithPointer(c);if(f)if(e!=this.currentItem[0]&&this.placeholder[f==1?"next":"prev"]()[0]!=e&&!d.ui.contains(this.placeholder[0],e)&&(this.options.type=="semi-dynamic"?!d.ui.contains(this.element[0],e):true)){this.direction=f==1?"down":"up";if(this.options.tolerance=="pointer"||this._intersectsWithSides(c))this._rearrange(a,
c);else break;this._trigger("change",a,this._uiHash());break}}this._contactContainers(a);d.ui.ddmanager&&d.ui.ddmanager.drag(this,a);this._trigger("sort",a,this._uiHash());this.lastPositionAbs=this.positionAbs;return false},_mouseStop:function(a,b){if(a){d.ui.ddmanager&&!this.options.dropBehaviour&&d.ui.ddmanager.drop(this,a);if(this.options.revert){var c=this;b=c.placeholder.offset();c.reverting=true;d(this.helper).animate({left:b.left-this.offset.parent.left-c.margins.left+(this.offsetParent[0]==
document.body?0:this.offsetParent[0].scrollLeft),top:b.top-this.offset.parent.top-c.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){c._clear(a)})}else this._clear(a,b);return false}},cancel:function(){var a=this;if(this.dragging){this._mouseUp();this.options.helper=="original"?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var b=this.containers.length-1;b>=0;b--){this.containers[b]._trigger("deactivate",
null,a._uiHash(this));if(this.containers[b].containerCache.over){this.containers[b]._trigger("out",null,a._uiHash(this));this.containers[b].containerCache.over=0}}}this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]);this.options.helper!="original"&&this.helper&&this.helper[0].parentNode&&this.helper.remove();d.extend(this,{helper:null,dragging:false,reverting:false,_noFinalSort:null});this.domPosition.prev?d(this.domPosition.prev).after(this.currentItem):
d(this.domPosition.parent).prepend(this.currentItem);return this},serialize:function(a){var b=this._getItemsAsjQuery(a&&a.connected),c=[];a=a||{};d(b).each(function(){var e=(d(a.item||this).attr(a.attribute||"id")||"").match(a.expression||/(.+)[-=_](.+)/);if(e)c.push((a.key||e[1]+"[]")+"="+(a.key&&a.expression?e[1]:e[2]))});return c.join("&")},toArray:function(a){var b=this._getItemsAsjQuery(a&&a.connected),c=[];a=a||{};b.each(function(){c.push(d(a.item||this).attr(a.attribute||"id")||"")});return c},
_intersectsWith:function(a){var b=this.positionAbs.left,c=b+this.helperProportions.width,e=this.positionAbs.top,f=e+this.helperProportions.height,g=a.left,h=g+a.width,i=a.top,k=i+a.height,j=this.offset.click.top,l=this.offset.click.left;j=e+j>i&&e+j<k&&b+l>g&&b+l<h;return this.options.tolerance=="pointer"||this.options.forcePointerForContainers||this.options.tolerance!="pointer"&&this.helperProportions[this.floating?"width":"height"]>a[this.floating?"width":"height"]?j:g<b+this.helperProportions.width/
2&&c-this.helperProportions.width/2<h&&i<e+this.helperProportions.height/2&&f-this.helperProportions.height/2<k},_intersectsWithPointer:function(a){var b=d.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,a.top,a.height);a=d.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,a.left,a.width);b=b&&a;a=this._getDragVerticalDirection();var c=this._getDragHorizontalDirection();if(!b)return false;return this.floating?c&&c=="right"||a=="down"?2:1:a&&(a=="down"?2:1)},_intersectsWithSides:function(a){var b=
d.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,a.top+a.height/2,a.height);a=d.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,a.left+a.width/2,a.width);var c=this._getDragVerticalDirection(),e=this._getDragHorizontalDirection();return this.floating&&e?e=="right"&&a||e=="left"&&!a:c&&(c=="down"&&b||c=="up"&&!b)},_getDragVerticalDirection:function(){var a=this.positionAbs.top-this.lastPositionAbs.top;return a!=0&&(a>0?"down":"up")},_getDragHorizontalDirection:function(){var a=
this.positionAbs.left-this.lastPositionAbs.left;return a!=0&&(a>0?"right":"left")},refresh:function(a){this._refreshItems(a);this.refreshPositions();return this},_connectWith:function(){var a=this.options;return a.connectWith.constructor==String?[a.connectWith]:a.connectWith},_getItemsAsjQuery:function(a){var b=[],c=[],e=this._connectWith();if(e&&a)for(a=e.length-1;a>=0;a--)for(var f=d(e[a]),g=f.length-1;g>=0;g--){var h=d.data(f[g],"sortable");if(h&&h!=this&&!h.options.disabled)c.push([d.isFunction(h.options.items)?
h.options.items.call(h.element):d(h.options.items,h.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),h])}c.push([d.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):d(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);for(a=c.length-1;a>=0;a--)c[a][0].each(function(){b.push(this)});return d(b)},_removeCurrentsFromItems:function(){for(var a=this.currentItem.find(":data(sortable-item)"),
b=0;b<this.items.length;b++)for(var c=0;c<a.length;c++)a[c]==this.items[b].item[0]&&this.items.splice(b,1)},_refreshItems:function(a){this.items=[];this.containers=[this];var b=this.items,c=[[d.isFunction(this.options.items)?this.options.items.call(this.element[0],a,{item:this.currentItem}):d(this.options.items,this.element),this]],e=this._connectWith();if(e)for(var f=e.length-1;f>=0;f--)for(var g=d(e[f]),h=g.length-1;h>=0;h--){var i=d.data(g[h],"sortable");if(i&&i!=this&&!i.options.disabled){c.push([d.isFunction(i.options.items)?
i.options.items.call(i.element[0],a,{item:this.currentItem}):d(i.options.items,i.element),i]);this.containers.push(i)}}for(f=c.length-1;f>=0;f--){a=c[f][1];e=c[f][0];h=0;for(g=e.length;h<g;h++){i=d(e[h]);i.data("sortable-item",a);b.push({item:i,instance:a,width:0,height:0,left:0,top:0})}}},refreshPositions:function(a){if(this.offsetParent&&this.helper)this.offset.parent=this._getParentOffset();for(var b=this.items.length-1;b>=0;b--){var c=this.items[b],e=this.options.toleranceElement?d(this.options.toleranceElement,
c.item):c.item;if(!a){c.width=e.outerWidth();c.height=e.outerHeight()}e=e.offset();c.left=e.left;c.top=e.top}if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(b=this.containers.length-1;b>=0;b--){e=this.containers[b].element.offset();this.containers[b].containerCache.left=e.left;this.containers[b].containerCache.top=e.top;this.containers[b].containerCache.width=this.containers[b].element.outerWidth();this.containers[b].containerCache.height=
this.containers[b].element.outerHeight()}return this},_createPlaceholder:function(a){var b=a||this,c=b.options;if(!c.placeholder||c.placeholder.constructor==String){var e=c.placeholder;c.placeholder={element:function(){var f=d(document.createElement(b.currentItem[0].nodeName)).addClass(e||b.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];if(!e)f.style.visibility="hidden";return f},update:function(f,g){if(!(e&&!c.forcePlaceholderSize)){g.height()||g.height(b.currentItem.innerHeight()-
parseInt(b.currentItem.css("paddingTop")||0,10)-parseInt(b.currentItem.css("paddingBottom")||0,10));g.width()||g.width(b.currentItem.innerWidth()-parseInt(b.currentItem.css("paddingLeft")||0,10)-parseInt(b.currentItem.css("paddingRight")||0,10))}}}}b.placeholder=d(c.placeholder.element.call(b.element,b.currentItem));b.currentItem.after(b.placeholder);c.placeholder.update(b,b.placeholder)},_contactContainers:function(a){for(var b=null,c=null,e=this.containers.length-1;e>=0;e--)if(!d.ui.contains(this.currentItem[0],
this.containers[e].element[0]))if(this._intersectsWith(this.containers[e].containerCache)){if(!(b&&d.ui.contains(this.containers[e].element[0],b.element[0]))){b=this.containers[e];c=e}}else if(this.containers[e].containerCache.over){this.containers[e]._trigger("out",a,this._uiHash(this));this.containers[e].containerCache.over=0}if(b)if(this.containers.length===1){this.containers[c]._trigger("over",a,this._uiHash(this));this.containers[c].containerCache.over=1}else if(this.currentContainer!=this.containers[c]){b=
1E4;e=null;for(var f=this.positionAbs[this.containers[c].floating?"left":"top"],g=this.items.length-1;g>=0;g--)if(d.ui.contains(this.containers[c].element[0],this.items[g].item[0])){var h=this.items[g][this.containers[c].floating?"left":"top"];if(Math.abs(h-f)<b){b=Math.abs(h-f);e=this.items[g]}}if(e||this.options.dropOnEmpty){this.currentContainer=this.containers[c];e?this._rearrange(a,e,null,true):this._rearrange(a,null,this.containers[c].element,true);this._trigger("change",a,this._uiHash());this.containers[c]._trigger("change",
a,this._uiHash(this));this.options.placeholder.update(this.currentContainer,this.placeholder);this.containers[c]._trigger("over",a,this._uiHash(this));this.containers[c].containerCache.over=1}}},_createHelper:function(a){var b=this.options;a=d.isFunction(b.helper)?d(b.helper.apply(this.element[0],[a,this.currentItem])):b.helper=="clone"?this.currentItem.clone():this.currentItem;a.parents("body").length||d(b.appendTo!="parent"?b.appendTo:this.currentItem[0].parentNode)[0].appendChild(a[0]);if(a[0]==
this.currentItem[0])this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")};if(a[0].style.width==""||b.forceHelperSize)a.width(this.currentItem.width());if(a[0].style.height==""||b.forceHelperSize)a.height(this.currentItem.height());return a},_adjustOffsetFromHelper:function(a){if(typeof a=="string")a=a.split(" ");if(d.isArray(a))a={left:+a[0],top:+a[1]||
0};if("left"in a)this.offset.click.left=a.left+this.margins.left;if("right"in a)this.offset.click.left=this.helperProportions.width-a.right+this.margins.left;if("top"in a)this.offset.click.top=a.top+this.margins.top;if("bottom"in a)this.offset.click.top=this.helperProportions.height-a.bottom+this.margins.top},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var a=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],
this.offsetParent[0])){a.left+=this.scrollParent.scrollLeft();a.top+=this.scrollParent.scrollTop()}if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&d.browser.msie)a={top:0,left:0};return{top:a.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:a.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var a=this.currentItem.position();return{top:a.top-
(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:a.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var a=this.options;
if(a.containment=="parent")a.containment=this.helper[0].parentNode;if(a.containment=="document"||a.containment=="window")this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,d(a.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(d(a.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(a.containment)){var b=
d(a.containment)[0];a=d(a.containment).offset();var c=d(b).css("overflow")!="hidden";this.containment=[a.left+(parseInt(d(b).css("borderLeftWidth"),10)||0)+(parseInt(d(b).css("paddingLeft"),10)||0)-this.margins.left,a.top+(parseInt(d(b).css("borderTopWidth"),10)||0)+(parseInt(d(b).css("paddingTop"),10)||0)-this.margins.top,a.left+(c?Math.max(b.scrollWidth,b.offsetWidth):b.offsetWidth)-(parseInt(d(b).css("borderLeftWidth"),10)||0)-(parseInt(d(b).css("paddingRight"),10)||0)-this.helperProportions.width-
this.margins.left,a.top+(c?Math.max(b.scrollHeight,b.offsetHeight):b.offsetHeight)-(parseInt(d(b).css("borderTopWidth"),10)||0)-(parseInt(d(b).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(a,b){if(!b)b=this.position;a=a=="absolute"?1:-1;var c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,e=/(html|body)/i.test(c[0].tagName);return{top:b.top+
this.offset.relative.top*a+this.offset.parent.top*a-(d.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():e?0:c.scrollTop())*a),left:b.left+this.offset.relative.left*a+this.offset.parent.left*a-(d.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():e?0:c.scrollLeft())*a)}},_generatePosition:function(a){var b=this.options,c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],
this.offsetParent[0]))?this.offsetParent:this.scrollParent,e=/(html|body)/i.test(c[0].tagName);if(this.cssPosition=="relative"&&!(this.scrollParent[0]!=document&&this.scrollParent[0]!=this.offsetParent[0]))this.offset.relative=this._getRelativeOffset();var f=a.pageX,g=a.pageY;if(this.originalPosition){if(this.containment){if(a.pageX-this.offset.click.left<this.containment[0])f=this.containment[0]+this.offset.click.left;if(a.pageY-this.offset.click.top<this.containment[1])g=this.containment[1]+this.offset.click.top;
if(a.pageX-this.offset.click.left>this.containment[2])f=this.containment[2]+this.offset.click.left;if(a.pageY-this.offset.click.top>this.containment[3])g=this.containment[3]+this.offset.click.top}if(b.grid){g=this.originalPageY+Math.round((g-this.originalPageY)/b.grid[1])*b.grid[1];g=this.containment?!(g-this.offset.click.top<this.containment[1]||g-this.offset.click.top>this.containment[3])?g:!(g-this.offset.click.top<this.containment[1])?g-b.grid[1]:g+b.grid[1]:g;f=this.originalPageX+Math.round((f-
this.originalPageX)/b.grid[0])*b.grid[0];f=this.containment?!(f-this.offset.click.left<this.containment[0]||f-this.offset.click.left>this.containment[2])?f:!(f-this.offset.click.left<this.containment[0])?f-b.grid[0]:f+b.grid[0]:f}}return{top:g-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(d.browser.safari&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollTop():e?0:c.scrollTop()),left:f-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+
(d.browser.safari&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():e?0:c.scrollLeft())}},_rearrange:function(a,b,c,e){c?c[0].appendChild(this.placeholder[0]):b.item[0].parentNode.insertBefore(this.placeholder[0],this.direction=="down"?b.item[0]:b.item[0].nextSibling);this.counter=this.counter?++this.counter:1;var f=this,g=this.counter;window.setTimeout(function(){g==f.counter&&f.refreshPositions(!e)},0)},_clear:function(a,b){this.reverting=false;var c=[];!this._noFinalSort&&
this.currentItem[0].parentNode&&this.placeholder.before(this.currentItem);this._noFinalSort=null;if(this.helper[0]==this.currentItem[0]){for(var e in this._storedCSS)if(this._storedCSS[e]=="auto"||this._storedCSS[e]=="static")this._storedCSS[e]="";this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();this.fromOutside&&!b&&c.push(function(f){this._trigger("receive",f,this._uiHash(this.fromOutside))});if((this.fromOutside||this.domPosition.prev!=this.currentItem.prev().not(".ui-sortable-helper")[0]||
this.domPosition.parent!=this.currentItem.parent()[0])&&!b)c.push(function(f){this._trigger("update",f,this._uiHash())});if(!d.ui.contains(this.element[0],this.currentItem[0])){b||c.push(function(f){this._trigger("remove",f,this._uiHash())});for(e=this.containers.length-1;e>=0;e--)if(d.ui.contains(this.containers[e].element[0],this.currentItem[0])&&!b){c.push(function(f){return function(g){f._trigger("receive",g,this._uiHash(this))}}.call(this,this.containers[e]));c.push(function(f){return function(g){f._trigger("update",
g,this._uiHash(this))}}.call(this,this.containers[e]))}}for(e=this.containers.length-1;e>=0;e--){b||c.push(function(f){return function(g){f._trigger("deactivate",g,this._uiHash(this))}}.call(this,this.containers[e]));if(this.containers[e].containerCache.over){c.push(function(f){return function(g){f._trigger("out",g,this._uiHash(this))}}.call(this,this.containers[e]));this.containers[e].containerCache.over=0}}this._storedCursor&&d("body").css("cursor",this._storedCursor);this._storedOpacity&&this.helper.css("opacity",
this._storedOpacity);if(this._storedZIndex)this.helper.css("zIndex",this._storedZIndex=="auto"?"":this._storedZIndex);this.dragging=false;if(this.cancelHelperRemoval){if(!b){this._trigger("beforeStop",a,this._uiHash());for(e=0;e<c.length;e++)c[e].call(this,a);this._trigger("stop",a,this._uiHash())}return false}b||this._trigger("beforeStop",a,this._uiHash());this.placeholder[0].parentNode.removeChild(this.placeholder[0]);this.helper[0]!=this.currentItem[0]&&this.helper.remove();this.helper=null;if(!b){for(e=
0;e<c.length;e++)c[e].call(this,a);this._trigger("stop",a,this._uiHash())}this.fromOutside=false;return true},_trigger:function(){d.Widget.prototype._trigger.apply(this,arguments)===false&&this.cancel()},_uiHash:function(a){var b=a||this;return{helper:b.helper,placeholder:b.placeholder||d([]),position:b.position,originalPosition:b.originalPosition,offset:b.positionAbs,item:b.currentItem,sender:a?a.element:null}}});d.extend(d.ui.sortable,{version:"1.8.1"})})(jQuery);
jQuery.effects||function(f){function k(c){var a;if(c&&c.constructor==Array&&c.length==3)return c;if(a=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(c))return[parseInt(a[1],10),parseInt(a[2],10),parseInt(a[3],10)];if(a=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(c))return[parseFloat(a[1])*2.55,parseFloat(a[2])*2.55,parseFloat(a[3])*2.55];if(a=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(c))return[parseInt(a[1],
16),parseInt(a[2],16),parseInt(a[3],16)];if(a=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(c))return[parseInt(a[1]+a[1],16),parseInt(a[2]+a[2],16),parseInt(a[3]+a[3],16)];if(/rgba\(0, 0, 0, 0\)/.exec(c))return l.transparent;return l[f.trim(c).toLowerCase()]}function q(c,a){var b;do{b=f.curCSS(c,a);if(b!=""&&b!="transparent"||f.nodeName(c,"body"))break;a="backgroundColor"}while(c=c.parentNode);return k(b)}function m(){var c=document.defaultView?document.defaultView.getComputedStyle(this,null):this.currentStyle,
a={},b,d;if(c&&c.length&&c[0]&&c[c[0]])for(var e=c.length;e--;){b=c[e];if(typeof c[b]=="string"){d=b.replace(/\-(\w)/g,function(g,h){return h.toUpperCase()});a[d]=c[b]}}else for(b in c)if(typeof c[b]==="string")a[b]=c[b];return a}function n(c){var a,b;for(a in c){b=c[a];if(b==null||f.isFunction(b)||a in r||/scrollbar/.test(a)||!/color/i.test(a)&&isNaN(parseFloat(b)))delete c[a]}return c}function s(c,a){var b={_:0},d;for(d in a)if(c[d]!=a[d])b[d]=a[d];return b}function j(c,a,b,d){if(typeof c=="object"){d=
a;b=null;a=c;c=a.effect}if(f.isFunction(a)){d=a;b=null;a={}}if(f.isFunction(b)){d=b;b=null}if(typeof a=="number"||f.fx.speeds[a]){d=b;b=a;a={}}a=a||{};b=b||a.duration;b=f.fx.off?0:typeof b=="number"?b:f.fx.speeds[b]||f.fx.speeds._default;d=d||a.complete;return[c,a,b,d]}f.effects={};f.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","color","outlineColor"],function(c,a){f.fx.step[a]=function(b){if(!b.colorInit){b.start=q(b.elem,a);b.end=k(b.end);b.colorInit=
true}b.elem.style[a]="rgb("+Math.max(Math.min(parseInt(b.pos*(b.end[0]-b.start[0])+b.start[0],10),255),0)+","+Math.max(Math.min(parseInt(b.pos*(b.end[1]-b.start[1])+b.start[1],10),255),0)+","+Math.max(Math.min(parseInt(b.pos*(b.end[2]-b.start[2])+b.start[2],10),255),0)+")"}});var l={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,
183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,
165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]},o=["add","remove","toggle"],r={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};f.effects.animateClass=function(c,a,b,d){if(f.isFunction(b)){d=b;b=null}return this.each(function(){var e=f(this),g=e.attr("style")||" ",h=n(m.call(this)),p,t=e.attr("className");f.each(o,function(u,
i){c[i]&&e[i+"Class"](c[i])});p=n(m.call(this));e.attr("className",t);e.animate(s(h,p),a,b,function(){f.each(o,function(u,i){c[i]&&e[i+"Class"](c[i])});if(typeof e.attr("style")=="object"){e.attr("style").cssText="";e.attr("style").cssText=g}else e.attr("style",g);d&&d.apply(this,arguments)})})};f.fn.extend({_addClass:f.fn.addClass,addClass:function(c,a,b,d){return a?f.effects.animateClass.apply(this,[{add:c},a,b,d]):this._addClass(c)},_removeClass:f.fn.removeClass,removeClass:function(c,a,b,d){return a?
f.effects.animateClass.apply(this,[{remove:c},a,b,d]):this._removeClass(c)},_toggleClass:f.fn.toggleClass,toggleClass:function(c,a,b,d,e){return typeof a=="boolean"||a===undefined?b?f.effects.animateClass.apply(this,[a?{add:c}:{remove:c},b,d,e]):this._toggleClass(c,a):f.effects.animateClass.apply(this,[{toggle:c},a,b,d])},switchClass:function(c,a,b,d,e){return f.effects.animateClass.apply(this,[{add:a,remove:c},b,d,e])}});f.extend(f.effects,{version:"1.8.1",save:function(c,a){for(var b=0;b<a.length;b++)a[b]!==
null&&c.data("ec.storage."+a[b],c[0].style[a[b]])},restore:function(c,a){for(var b=0;b<a.length;b++)a[b]!==null&&c.css(a[b],c.data("ec.storage."+a[b]))},setMode:function(c,a){if(a=="toggle")a=c.is(":hidden")?"show":"hide";return a},getBaseline:function(c,a){var b;switch(c[0]){case "top":b=0;break;case "middle":b=0.5;break;case "bottom":b=1;break;default:b=c[0]/a.height}switch(c[1]){case "left":c=0;break;case "center":c=0.5;break;case "right":c=1;break;default:c=c[1]/a.width}return{x:c,y:b}},createWrapper:function(c){if(c.parent().is(".ui-effects-wrapper"))return c.parent();
var a={width:c.outerWidth(true),height:c.outerHeight(true),"float":c.css("float")},b=f("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0});c.wrap(b);b=c.parent();if(c.css("position")=="static"){b.css({position:"relative"});c.css({position:"relative"})}else{f.extend(a,{position:c.css("position"),zIndex:c.css("z-index")});f.each(["top","left","bottom","right"],function(d,e){a[e]=c.css(e);if(isNaN(parseInt(a[e],10)))a[e]="auto"});
c.css({position:"relative",top:0,left:0})}return b.css(a).show()},removeWrapper:function(c){if(c.parent().is(".ui-effects-wrapper"))return c.parent().replaceWith(c);return c},setTransition:function(c,a,b,d){d=d||{};f.each(a,function(e,g){unit=c.cssUnit(g);if(unit[0]>0)d[g]=unit[0]*b+unit[1]});return d}});f.fn.extend({effect:function(c){var a=j.apply(this,arguments);a={options:a[1],duration:a[2],callback:a[3]};var b=f.effects[c];return b&&!f.fx.off?b.call(this,a):this},_show:f.fn.show,show:function(c){if(!c||
typeof c=="number"||f.fx.speeds[c])return this._show.apply(this,arguments);else{var a=j.apply(this,arguments);a[1].mode="show";return this.effect.apply(this,a)}},_hide:f.fn.hide,hide:function(c){if(!c||typeof c=="number"||f.fx.speeds[c])return this._hide.apply(this,arguments);else{var a=j.apply(this,arguments);a[1].mode="hide";return this.effect.apply(this,a)}},__toggle:f.fn.toggle,toggle:function(c){if(!c||typeof c=="number"||f.fx.speeds[c]||typeof c=="boolean"||f.isFunction(c))return this.__toggle.apply(this,
arguments);else{var a=j.apply(this,arguments);a[1].mode="toggle";return this.effect.apply(this,a)}},cssUnit:function(c){var a=this.css(c),b=[];f.each(["em","px","%","pt"],function(d,e){if(a.indexOf(e)>0)b=[parseFloat(a),e]});return b}});f.easing.jswing=f.easing.swing;f.extend(f.easing,{def:"easeOutQuad",swing:function(c,a,b,d,e){return f.easing[f.easing.def](c,a,b,d,e)},easeInQuad:function(c,a,b,d,e){return d*(a/=e)*a+b},easeOutQuad:function(c,a,b,d,e){return-d*(a/=e)*(a-2)+b},easeInOutQuad:function(c,
a,b,d,e){if((a/=e/2)<1)return d/2*a*a+b;return-d/2*(--a*(a-2)-1)+b},easeInCubic:function(c,a,b,d,e){return d*(a/=e)*a*a+b},easeOutCubic:function(c,a,b,d,e){return d*((a=a/e-1)*a*a+1)+b},easeInOutCubic:function(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a*a+b;return d/2*((a-=2)*a*a+2)+b},easeInQuart:function(c,a,b,d,e){return d*(a/=e)*a*a*a+b},easeOutQuart:function(c,a,b,d,e){return-d*((a=a/e-1)*a*a*a-1)+b},easeInOutQuart:function(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a*a*a+b;return-d/2*((a-=2)*a*a*a-2)+
b},easeInQuint:function(c,a,b,d,e){return d*(a/=e)*a*a*a*a+b},easeOutQuint:function(c,a,b,d,e){return d*((a=a/e-1)*a*a*a*a+1)+b},easeInOutQuint:function(c,a,b,d,e){if((a/=e/2)<1)return d/2*a*a*a*a*a+b;return d/2*((a-=2)*a*a*a*a+2)+b},easeInSine:function(c,a,b,d,e){return-d*Math.cos(a/e*(Math.PI/2))+d+b},easeOutSine:function(c,a,b,d,e){return d*Math.sin(a/e*(Math.PI/2))+b},easeInOutSine:function(c,a,b,d,e){return-d/2*(Math.cos(Math.PI*a/e)-1)+b},easeInExpo:function(c,a,b,d,e){return a==0?b:d*Math.pow(2,
10*(a/e-1))+b},easeOutExpo:function(c,a,b,d,e){return a==e?b+d:d*(-Math.pow(2,-10*a/e)+1)+b},easeInOutExpo:function(c,a,b,d,e){if(a==0)return b;if(a==e)return b+d;if((a/=e/2)<1)return d/2*Math.pow(2,10*(a-1))+b;return d/2*(-Math.pow(2,-10*--a)+2)+b},easeInCirc:function(c,a,b,d,e){return-d*(Math.sqrt(1-(a/=e)*a)-1)+b},easeOutCirc:function(c,a,b,d,e){return d*Math.sqrt(1-(a=a/e-1)*a)+b},easeInOutCirc:function(c,a,b,d,e){if((a/=e/2)<1)return-d/2*(Math.sqrt(1-a*a)-1)+b;return d/2*(Math.sqrt(1-(a-=2)*
a)+1)+b},easeInElastic:function(c,a,b,d,e){c=1.70158;var g=0,h=d;if(a==0)return b;if((a/=e)==1)return b+d;g||(g=e*0.3);if(h<Math.abs(d)){h=d;c=g/4}else c=g/(2*Math.PI)*Math.asin(d/h);return-(h*Math.pow(2,10*(a-=1))*Math.sin((a*e-c)*2*Math.PI/g))+b},easeOutElastic:function(c,a,b,d,e){c=1.70158;var g=0,h=d;if(a==0)return b;if((a/=e)==1)return b+d;g||(g=e*0.3);if(h<Math.abs(d)){h=d;c=g/4}else c=g/(2*Math.PI)*Math.asin(d/h);return h*Math.pow(2,-10*a)*Math.sin((a*e-c)*2*Math.PI/g)+d+b},easeInOutElastic:function(c,
a,b,d,e){c=1.70158;var g=0,h=d;if(a==0)return b;if((a/=e/2)==2)return b+d;g||(g=e*0.3*1.5);if(h<Math.abs(d)){h=d;c=g/4}else c=g/(2*Math.PI)*Math.asin(d/h);if(a<1)return-0.5*h*Math.pow(2,10*(a-=1))*Math.sin((a*e-c)*2*Math.PI/g)+b;return h*Math.pow(2,-10*(a-=1))*Math.sin((a*e-c)*2*Math.PI/g)*0.5+d+b},easeInBack:function(c,a,b,d,e,g){if(g==undefined)g=1.70158;return d*(a/=e)*a*((g+1)*a-g)+b},easeOutBack:function(c,a,b,d,e,g){if(g==undefined)g=1.70158;return d*((a=a/e-1)*a*((g+1)*a+g)+1)+b},easeInOutBack:function(c,
a,b,d,e,g){if(g==undefined)g=1.70158;if((a/=e/2)<1)return d/2*a*a*(((g*=1.525)+1)*a-g)+b;return d/2*((a-=2)*a*(((g*=1.525)+1)*a+g)+2)+b},easeInBounce:function(c,a,b,d,e){return d-f.easing.easeOutBounce(c,e-a,0,d,e)+b},easeOutBounce:function(c,a,b,d,e){return(a/=e)<1/2.75?d*7.5625*a*a+b:a<2/2.75?d*(7.5625*(a-=1.5/2.75)*a+0.75)+b:a<2.5/2.75?d*(7.5625*(a-=2.25/2.75)*a+0.9375)+b:d*(7.5625*(a-=2.625/2.75)*a+0.984375)+b},easeInOutBounce:function(c,a,b,d,e){if(a<e/2)return f.easing.easeInBounce(c,a*2,0,
d,e)*0.5+b;return f.easing.easeOutBounce(c,a*2-e,0,d,e)*0.5+d*0.5+b}})}(jQuery);
(function(b){b.effects.blind=function(c){return this.queue(function(){var a=b(this),g=["position","top","left"],f=b.effects.setMode(a,c.options.mode||"hide"),d=c.options.direction||"vertical";b.effects.save(a,g);a.show();var e=b.effects.createWrapper(a).css({overflow:"hidden"}),h=d=="vertical"?"height":"width";d=d=="vertical"?e.height():e.width();f=="show"&&e.css(h,0);var i={};i[h]=f=="show"?d:0;e.animate(i,c.duration,c.options.easing,function(){f=="hide"&&a.hide();b.effects.restore(a,g);b.effects.removeWrapper(a);
c.callback&&c.callback.apply(a[0],arguments);a.dequeue()})})}})(jQuery);
(function(e){e.effects.bounce=function(b){return this.queue(function(){var a=e(this),l=["position","top","left"],h=e.effects.setMode(a,b.options.mode||"effect"),d=b.options.direction||"up",c=b.options.distance||20,m=b.options.times||5,i=b.duration||250;/show|hide/.test(h)&&l.push("opacity");e.effects.save(a,l);a.show();e.effects.createWrapper(a);var f=d=="up"||d=="down"?"top":"left";d=d=="up"||d=="left"?"pos":"neg";c=b.options.distance||(f=="top"?a.outerHeight({margin:true})/3:a.outerWidth({margin:true})/
3);if(h=="show")a.css("opacity",0).css(f,d=="pos"?-c:c);if(h=="hide")c/=m*2;h!="hide"&&m--;if(h=="show"){var g={opacity:1};g[f]=(d=="pos"?"+=":"-=")+c;a.animate(g,i/2,b.options.easing);c/=2;m--}for(g=0;g<m;g++){var j={},k={};j[f]=(d=="pos"?"-=":"+=")+c;k[f]=(d=="pos"?"+=":"-=")+c;a.animate(j,i/2,b.options.easing).animate(k,i/2,b.options.easing);c=h=="hide"?c*2:c/2}if(h=="hide"){g={opacity:0};g[f]=(d=="pos"?"-=":"+=")+c;a.animate(g,i/2,b.options.easing,function(){a.hide();e.effects.restore(a,l);e.effects.removeWrapper(a);
b.callback&&b.callback.apply(this,arguments)})}else{j={};k={};j[f]=(d=="pos"?"-=":"+=")+c;k[f]=(d=="pos"?"+=":"-=")+c;a.animate(j,i/2,b.options.easing).animate(k,i/2,b.options.easing,function(){e.effects.restore(a,l);e.effects.removeWrapper(a);b.callback&&b.callback.apply(this,arguments)})}a.queue("fx",function(){a.dequeue()});a.dequeue()})}})(jQuery);
(function(b){b.effects.clip=function(e){return this.queue(function(){var a=b(this),i=["position","top","left","height","width"],f=b.effects.setMode(a,e.options.mode||"hide"),c=e.options.direction||"vertical";b.effects.save(a,i);a.show();var d=b.effects.createWrapper(a).css({overflow:"hidden"});d=a[0].tagName=="IMG"?d:a;var g={size:c=="vertical"?"height":"width",position:c=="vertical"?"top":"left"};c=c=="vertical"?d.height():d.width();if(f=="show"){d.css(g.size,0);d.css(g.position,c/2)}var h={};h[g.size]=
f=="show"?c:0;h[g.position]=f=="show"?0:c/2;d.animate(h,{queue:false,duration:e.duration,easing:e.options.easing,complete:function(){f=="hide"&&a.hide();b.effects.restore(a,i);b.effects.removeWrapper(a);e.callback&&e.callback.apply(a[0],arguments);a.dequeue()}})})}})(jQuery);
(function(c){c.effects.drop=function(d){return this.queue(function(){var a=c(this),h=["position","top","left","opacity"],e=c.effects.setMode(a,d.options.mode||"hide"),b=d.options.direction||"left";c.effects.save(a,h);a.show();c.effects.createWrapper(a);var f=b=="up"||b=="down"?"top":"left";b=b=="up"||b=="left"?"pos":"neg";var g=d.options.distance||(f=="top"?a.outerHeight({margin:true})/2:a.outerWidth({margin:true})/2);if(e=="show")a.css("opacity",0).css(f,b=="pos"?-g:g);var i={opacity:e=="show"?1:
0};i[f]=(e=="show"?b=="pos"?"+=":"-=":b=="pos"?"-=":"+=")+g;a.animate(i,{queue:false,duration:d.duration,easing:d.options.easing,complete:function(){e=="hide"&&a.hide();c.effects.restore(a,h);c.effects.removeWrapper(a);d.callback&&d.callback.apply(this,arguments);a.dequeue()}})})}})(jQuery);
(function(j){j.effects.explode=function(a){return this.queue(function(){var c=a.options.pieces?Math.round(Math.sqrt(a.options.pieces)):3,d=a.options.pieces?Math.round(Math.sqrt(a.options.pieces)):3;a.options.mode=a.options.mode=="toggle"?j(this).is(":visible")?"hide":"show":a.options.mode;var b=j(this).show().css("visibility","hidden"),g=b.offset();g.top-=parseInt(b.css("marginTop"),10)||0;g.left-=parseInt(b.css("marginLeft"),10)||0;for(var h=b.outerWidth(true),i=b.outerHeight(true),e=0;e<c;e++)for(var f=
0;f<d;f++)b.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-f*(h/d),top:-e*(i/c)}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:h/d,height:i/c,left:g.left+f*(h/d)+(a.options.mode=="show"?(f-Math.floor(d/2))*(h/d):0),top:g.top+e*(i/c)+(a.options.mode=="show"?(e-Math.floor(c/2))*(i/c):0),opacity:a.options.mode=="show"?0:1}).animate({left:g.left+f*(h/d)+(a.options.mode=="show"?0:(f-Math.floor(d/2))*(h/d)),top:g.top+
e*(i/c)+(a.options.mode=="show"?0:(e-Math.floor(c/2))*(i/c)),opacity:a.options.mode=="show"?1:0},a.duration||500);setTimeout(function(){a.options.mode=="show"?b.css({visibility:"visible"}):b.css({visibility:"visible"}).hide();a.callback&&a.callback.apply(b[0]);b.dequeue();j("div.ui-effects-explode").remove()},a.duration||500)})}})(jQuery);
(function(b){b.effects.fade=function(a){return this.queue(function(){var c=b(this),d=b.effects.setMode(c,a.options.mode||"hide");c.animate({opacity:d},{queue:false,duration:a.duration,easing:a.options.easing,complete:function(){a.callback&&a.callback.apply(this,arguments);c.dequeue()}})})}})(jQuery);
(function(c){c.effects.fold=function(a){return this.queue(function(){var b=c(this),j=["position","top","left"],d=c.effects.setMode(b,a.options.mode||"hide"),g=a.options.size||15,h=!!a.options.horizFirst,k=a.duration?a.duration/2:c.fx.speeds._default/2;c.effects.save(b,j);b.show();var e=c.effects.createWrapper(b).css({overflow:"hidden"}),f=d=="show"!=h,l=f?["width","height"]:["height","width"];f=f?[e.width(),e.height()]:[e.height(),e.width()];var i=/([0-9]+)%/.exec(g);if(i)g=parseInt(i[1],10)/100*
f[d=="hide"?0:1];if(d=="show")e.css(h?{height:0,width:g}:{height:g,width:0});h={};i={};h[l[0]]=d=="show"?f[0]:g;i[l[1]]=d=="show"?f[1]:0;e.animate(h,k,a.options.easing).animate(i,k,a.options.easing,function(){d=="hide"&&b.hide();c.effects.restore(b,j);c.effects.removeWrapper(b);a.callback&&a.callback.apply(b[0],arguments);b.dequeue()})})}})(jQuery);
(function(b){b.effects.highlight=function(c){return this.queue(function(){var a=b(this),e=["backgroundImage","backgroundColor","opacity"],d=b.effects.setMode(a,c.options.mode||"show"),f={backgroundColor:a.css("backgroundColor")};if(d=="hide")f.opacity=0;b.effects.save(a,e);a.show().css({backgroundImage:"none",backgroundColor:c.options.color||"#ffff99"}).animate(f,{queue:false,duration:c.duration,easing:c.options.easing,complete:function(){d=="hide"&&a.hide();b.effects.restore(a,e);d=="show"&&!b.support.opacity&&
this.style.removeAttribute("filter");c.callback&&c.callback.apply(this,arguments);a.dequeue()}})})}})(jQuery);
(function(d){d.effects.pulsate=function(a){return this.queue(function(){var b=d(this),c=d.effects.setMode(b,a.options.mode||"show");times=(a.options.times||5)*2-1;duration=a.duration?a.duration/2:d.fx.speeds._default/2;isVisible=b.is(":visible");animateTo=0;if(!isVisible){b.css("opacity",0).show();animateTo=1}if(c=="hide"&&isVisible||c=="show"&&!isVisible)times--;for(c=0;c<times;c++){b.animate({opacity:animateTo},duration,a.options.easing);animateTo=(animateTo+1)%2}b.animate({opacity:animateTo},duration,
a.options.easing,function(){animateTo==0&&b.hide();a.callback&&a.callback.apply(this,arguments)});b.queue("fx",function(){b.dequeue()}).dequeue()})}})(jQuery);
(function(c){c.effects.puff=function(b){return this.queue(function(){var a=c(this),e=c.effects.setMode(a,b.options.mode||"hide"),g=parseInt(b.options.percent,10)||150,h=g/100,i={height:a.height(),width:a.width()};c.extend(b.options,{fade:true,mode:e,percent:e=="hide"?g:100,from:e=="hide"?i:{height:i.height*h,width:i.width*h}});a.effect("scale",b.options,b.duration,b.callback);a.dequeue()})};c.effects.scale=function(b){return this.queue(function(){var a=c(this),e=c.extend(true,{},b.options),g=c.effects.setMode(a,
b.options.mode||"effect"),h=parseInt(b.options.percent,10)||(parseInt(b.options.percent,10)==0?0:g=="hide"?0:100),i=b.options.direction||"both",f=b.options.origin;if(g!="effect"){e.origin=f||["middle","center"];e.restore=true}f={height:a.height(),width:a.width()};a.from=b.options.from||(g=="show"?{height:0,width:0}:f);h={y:i!="horizontal"?h/100:1,x:i!="vertical"?h/100:1};a.to={height:f.height*h.y,width:f.width*h.x};if(b.options.fade){if(g=="show"){a.from.opacity=0;a.to.opacity=1}if(g=="hide"){a.from.opacity=
1;a.to.opacity=0}}e.from=a.from;e.to=a.to;e.mode=g;a.effect("size",e,b.duration,b.callback);a.dequeue()})};c.effects.size=function(b){return this.queue(function(){var a=c(this),e=["position","top","left","width","height","overflow","opacity"],g=["position","top","left","overflow","opacity"],h=["width","height","overflow"],i=["fontSize"],f=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],k=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],p=c.effects.setMode(a,
b.options.mode||"effect"),n=b.options.restore||false,m=b.options.scale||"both",l=b.options.origin,j={height:a.height(),width:a.width()};a.from=b.options.from||j;a.to=b.options.to||j;if(l){l=c.effects.getBaseline(l,j);a.from.top=(j.height-a.from.height)*l.y;a.from.left=(j.width-a.from.width)*l.x;a.to.top=(j.height-a.to.height)*l.y;a.to.left=(j.width-a.to.width)*l.x}var d={from:{y:a.from.height/j.height,x:a.from.width/j.width},to:{y:a.to.height/j.height,x:a.to.width/j.width}};if(m=="box"||m=="both"){if(d.from.y!=
d.to.y){e=e.concat(f);a.from=c.effects.setTransition(a,f,d.from.y,a.from);a.to=c.effects.setTransition(a,f,d.to.y,a.to)}if(d.from.x!=d.to.x){e=e.concat(k);a.from=c.effects.setTransition(a,k,d.from.x,a.from);a.to=c.effects.setTransition(a,k,d.to.x,a.to)}}if(m=="content"||m=="both")if(d.from.y!=d.to.y){e=e.concat(i);a.from=c.effects.setTransition(a,i,d.from.y,a.from);a.to=c.effects.setTransition(a,i,d.to.y,a.to)}c.effects.save(a,n?e:g);a.show();c.effects.createWrapper(a);a.css("overflow","hidden").css(a.from);
if(m=="content"||m=="both"){f=f.concat(["marginTop","marginBottom"]).concat(i);k=k.concat(["marginLeft","marginRight"]);h=e.concat(f).concat(k);a.find("*[width]").each(function(){child=c(this);n&&c.effects.save(child,h);var o={height:child.height(),width:child.width()};child.from={height:o.height*d.from.y,width:o.width*d.from.x};child.to={height:o.height*d.to.y,width:o.width*d.to.x};if(d.from.y!=d.to.y){child.from=c.effects.setTransition(child,f,d.from.y,child.from);child.to=c.effects.setTransition(child,
f,d.to.y,child.to)}if(d.from.x!=d.to.x){child.from=c.effects.setTransition(child,k,d.from.x,child.from);child.to=c.effects.setTransition(child,k,d.to.x,child.to)}child.css(child.from);child.animate(child.to,b.duration,b.options.easing,function(){n&&c.effects.restore(child,h)})})}a.animate(a.to,{queue:false,duration:b.duration,easing:b.options.easing,complete:function(){a.to.opacity===0&&a.css("opacity",a.from.opacity);p=="hide"&&a.hide();c.effects.restore(a,n?e:g);c.effects.removeWrapper(a);b.callback&&
b.callback.apply(this,arguments);a.dequeue()}})})}})(jQuery);
(function(d){d.effects.shake=function(a){return this.queue(function(){var b=d(this),j=["position","top","left"];d.effects.setMode(b,a.options.mode||"effect");var c=a.options.direction||"left",e=a.options.distance||20,l=a.options.times||3,f=a.duration||a.options.duration||140;d.effects.save(b,j);b.show();d.effects.createWrapper(b);var g=c=="up"||c=="down"?"top":"left",h=c=="up"||c=="left"?"pos":"neg";c={};var i={},k={};c[g]=(h=="pos"?"-=":"+=")+e;i[g]=(h=="pos"?"+=":"-=")+e*2;k[g]=(h=="pos"?"-=":"+=")+
e*2;b.animate(c,f,a.options.easing);for(e=1;e<l;e++)b.animate(i,f,a.options.easing).animate(k,f,a.options.easing);b.animate(i,f,a.options.easing).animate(c,f/2,a.options.easing,function(){d.effects.restore(b,j);d.effects.removeWrapper(b);a.callback&&a.callback.apply(this,arguments)});b.queue("fx",function(){b.dequeue()});b.dequeue()})}})(jQuery);
(function(c){c.effects.slide=function(d){return this.queue(function(){var a=c(this),h=["position","top","left"],e=c.effects.setMode(a,d.options.mode||"show"),b=d.options.direction||"left";c.effects.save(a,h);a.show();c.effects.createWrapper(a).css({overflow:"hidden"});var f=b=="up"||b=="down"?"top":"left";b=b=="up"||b=="left"?"pos":"neg";var g=d.options.distance||(f=="top"?a.outerHeight({margin:true}):a.outerWidth({margin:true}));if(e=="show")a.css(f,b=="pos"?-g:g);var i={};i[f]=(e=="show"?b=="pos"?
"+=":"-=":b=="pos"?"-=":"+=")+g;a.animate(i,{queue:false,duration:d.duration,easing:d.options.easing,complete:function(){e=="hide"&&a.hide();c.effects.restore(a,h);c.effects.removeWrapper(a);d.callback&&d.callback.apply(this,arguments);a.dequeue()}})})}})(jQuery);
(function(e){e.effects.transfer=function(a){return this.queue(function(){var b=e(this),c=e(a.options.to),d=c.offset();c={top:d.top,left:d.left,height:c.innerHeight(),width:c.innerWidth()};d=b.offset();var f=e('<div class="ui-effects-transfer"></div>').appendTo(document.body).addClass(a.options.className).css({top:d.top,left:d.left,height:b.innerHeight(),width:b.innerWidth(),position:"absolute"}).animate(c,a.duration,a.options.easing,function(){f.remove();a.callback&&a.callback.apply(b[0],arguments);
b.dequeue()})})}})(jQuery);
(function(c){c.widget("ui.accordion",{options:{active:0,animated:"slide",autoHeight:true,clearStyle:false,collapsible:false,event:"click",fillSpace:false,header:"> li > :first-child,> :not(li):even",icons:{header:"ui-icon-triangle-1-e",headerSelected:"ui-icon-triangle-1-s"},navigation:false,navigationFilter:function(){return this.href.toLowerCase()==location.href.toLowerCase()}},_create:function(){var a=this.options,b=this;this.running=0;this.element.addClass("ui-accordion ui-widget ui-helper-reset");
this.element[0].nodeName=="UL"&&this.element.children("li").addClass("ui-accordion-li-fix");this.headers=this.element.find(a.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all").bind("mouseenter.accordion",function(){c(this).addClass("ui-state-hover")}).bind("mouseleave.accordion",function(){c(this).removeClass("ui-state-hover")}).bind("focus.accordion",function(){c(this).addClass("ui-state-focus")}).bind("blur.accordion",function(){c(this).removeClass("ui-state-focus")});
this.headers.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom");if(a.navigation){var d=this.element.find("a").filter(a.navigationFilter);if(d.length){var f=d.closest(".ui-accordion-header");this.active=f.length?f:d.closest(".ui-accordion-content").prev()}}this.active=this._findActive(this.active||a.active).toggleClass("ui-state-default").toggleClass("ui-state-active").toggleClass("ui-corner-all").toggleClass("ui-corner-top");this.active.next().addClass("ui-accordion-content-active");
this._createIcons();this.resize();this.element.attr("role","tablist");this.headers.attr("role","tab").bind("keydown",function(g){return b._keydown(g)}).next().attr("role","tabpanel");this.headers.not(this.active||"").attr("aria-expanded","false").attr("tabIndex","-1").next().hide();this.active.length?this.active.attr("aria-expanded","true").attr("tabIndex","0"):this.headers.eq(0).attr("tabIndex","0");c.browser.safari||this.headers.find("a").attr("tabIndex","-1");a.event&&this.headers.bind(a.event+
".accordion",function(g){b._clickHandler.call(b,g,this);g.preventDefault()})},_createIcons:function(){var a=this.options;if(a.icons){c("<span/>").addClass("ui-icon "+a.icons.header).prependTo(this.headers);this.active.find(".ui-icon").toggleClass(a.icons.header).toggleClass(a.icons.headerSelected);this.element.addClass("ui-accordion-icons")}},_destroyIcons:function(){this.headers.children(".ui-icon").remove();this.element.removeClass("ui-accordion-icons")},destroy:function(){var a=this.options;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role").unbind(".accordion").removeData("accordion");
this.headers.unbind(".accordion").removeClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-corner-top").removeAttr("role").removeAttr("aria-expanded").removeAttr("tabIndex");this.headers.find("a").removeAttr("tabIndex");this._destroyIcons();var b=this.headers.next().css("display","").removeAttr("role").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active");if(a.autoHeight||a.fillHeight)b.css("height",
"");return this},_setOption:function(a,b){c.Widget.prototype._setOption.apply(this,arguments);a=="active"&&this.activate(b);if(a=="icons"){this._destroyIcons();b&&this._createIcons()}},_keydown:function(a){var b=c.ui.keyCode;if(!(this.options.disabled||a.altKey||a.ctrlKey)){var d=this.headers.length,f=this.headers.index(a.target),g=false;switch(a.keyCode){case b.RIGHT:case b.DOWN:g=this.headers[(f+1)%d];break;case b.LEFT:case b.UP:g=this.headers[(f-1+d)%d];break;case b.SPACE:case b.ENTER:this._clickHandler({target:a.target},
a.target);a.preventDefault()}if(g){c(a.target).attr("tabIndex","-1");c(g).attr("tabIndex","0");g.focus();return false}return true}},resize:function(){var a=this.options,b;if(a.fillSpace){if(c.browser.msie){var d=this.element.parent().css("overflow");this.element.parent().css("overflow","hidden")}b=this.element.parent().height();c.browser.msie&&this.element.parent().css("overflow",d);this.headers.each(function(){b-=c(this).outerHeight(true)});this.headers.next().each(function(){c(this).height(Math.max(0,
b-c(this).innerHeight()+c(this).height()))}).css("overflow","auto")}else if(a.autoHeight){b=0;this.headers.next().each(function(){b=Math.max(b,c(this).height())}).height(b)}return this},activate:function(a){this.options.active=a;a=this._findActive(a)[0];this._clickHandler({target:a},a);return this},_findActive:function(a){return a?typeof a=="number"?this.headers.filter(":eq("+a+")"):this.headers.not(this.headers.not(a)):a===false?c([]):this.headers.filter(":eq(0)")},_clickHandler:function(a,b){var d=
this.options;if(!d.disabled)if(a.target){a=c(a.currentTarget||b);b=a[0]==this.active[0];d.active=d.collapsible&&b?false:c(".ui-accordion-header",this.element).index(a);if(!(this.running||!d.collapsible&&b)){this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").find(".ui-icon").removeClass(d.icons.headerSelected).addClass(d.icons.header);if(!b){a.removeClass("ui-state-default ui-corner-all").addClass("ui-state-active ui-corner-top").find(".ui-icon").removeClass(d.icons.header).addClass(d.icons.headerSelected);
a.next().addClass("ui-accordion-content-active")}e=a.next();f=this.active.next();g={options:d,newHeader:b&&d.collapsible?c([]):a,oldHeader:this.active,newContent:b&&d.collapsible?c([]):e,oldContent:f};d=this.headers.index(this.active[0])>this.headers.index(a[0]);this.active=b?c([]):a;this._toggle(e,f,g,b,d)}}else if(d.collapsible){this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").find(".ui-icon").removeClass(d.icons.headerSelected).addClass(d.icons.header);
this.active.next().addClass("ui-accordion-content-active");var f=this.active.next(),g={options:d,newHeader:c([]),oldHeader:d.active,newContent:c([]),oldContent:f},e=this.active=c([]);this._toggle(e,f,g)}},_toggle:function(a,b,d,f,g){var e=this.options,k=this;this.toShow=a;this.toHide=b;this.data=d;var i=function(){if(k)return k._completed.apply(k,arguments)};this._trigger("changestart",null,this.data);this.running=b.size()===0?a.size():b.size();if(e.animated){d={};d=e.collapsible&&f?{toShow:c([]),
toHide:b,complete:i,down:g,autoHeight:e.autoHeight||e.fillSpace}:{toShow:a,toHide:b,complete:i,down:g,autoHeight:e.autoHeight||e.fillSpace};if(!e.proxied)e.proxied=e.animated;if(!e.proxiedDuration)e.proxiedDuration=e.duration;e.animated=c.isFunction(e.proxied)?e.proxied(d):e.proxied;e.duration=c.isFunction(e.proxiedDuration)?e.proxiedDuration(d):e.proxiedDuration;f=c.ui.accordion.animations;var h=e.duration,j=e.animated;if(j&&!f[j]&&!c.easing[j])j="slide";f[j]||(f[j]=function(l){this.slide(l,{easing:j,
duration:h||700})});f[j](d)}else{if(e.collapsible&&f)a.toggle();else{b.hide();a.show()}i(true)}b.prev().attr("aria-expanded","false").attr("tabIndex","-1").blur();a.prev().attr("aria-expanded","true").attr("tabIndex","0").focus()},_completed:function(a){var b=this.options;this.running=a?0:--this.running;if(!this.running){b.clearStyle&&this.toShow.add(this.toHide).css({height:"",overflow:""});this.toHide.removeClass("ui-accordion-content-active");this._trigger("change",null,this.data)}}});c.extend(c.ui.accordion,
{version:"1.8.1",animations:{slide:function(a,b){a=c.extend({easing:"swing",duration:300},a,b);if(a.toHide.size())if(a.toShow.size()){var d=a.toShow.css("overflow"),f=0,g={},e={},k;b=a.toShow;k=b[0].style.width;b.width(parseInt(b.parent().width(),10)-parseInt(b.css("paddingLeft"),10)-parseInt(b.css("paddingRight"),10)-(parseInt(b.css("borderLeftWidth"),10)||0)-(parseInt(b.css("borderRightWidth"),10)||0));c.each(["height","paddingTop","paddingBottom"],function(i,h){e[h]="hide";i=(""+c.css(a.toShow[0],
h)).match(/^([\d+-.]+)(.*)$/);g[h]={value:i[1],unit:i[2]||"px"}});a.toShow.css({height:0,overflow:"hidden"}).show();a.toHide.filter(":hidden").each(a.complete).end().filter(":visible").animate(e,{step:function(i,h){if(h.prop=="height")f=h.end-h.start===0?0:(h.now-h.start)/(h.end-h.start);a.toShow[0].style[h.prop]=f*g[h.prop].value+g[h.prop].unit},duration:a.duration,easing:a.easing,complete:function(){a.autoHeight||a.toShow.css("height","");a.toShow.css("width",k);a.toShow.css({overflow:d});a.complete()}})}else a.toHide.animate({height:"hide"},
a);else a.toShow.animate({height:"show"},a)},bounceslide:function(a){this.slide(a,{easing:a.down?"easeOutBounce":"swing",duration:a.down?1E3:200})}}})})(jQuery);
(function(e){e.widget("ui.autocomplete",{options:{minLength:1,delay:300},_create:function(){var a=this,b=this.element[0].ownerDocument;this.element.addClass("ui-autocomplete-input").attr("autocomplete","off").attr({role:"textbox","aria-autocomplete":"list","aria-haspopup":"true"}).bind("keydown.autocomplete",function(c){var d=e.ui.keyCode;switch(c.keyCode){case d.PAGE_UP:a._move("previousPage",c);break;case d.PAGE_DOWN:a._move("nextPage",c);break;case d.UP:a._move("previous",c);c.preventDefault();
break;case d.DOWN:a._move("next",c);c.preventDefault();break;case d.ENTER:a.menu.active&&c.preventDefault();case d.TAB:if(!a.menu.active)return;a.menu.select(c);break;case d.ESCAPE:a.element.val(a.term);a.close(c);break;case d.LEFT:case d.RIGHT:case d.SHIFT:case d.CONTROL:case d.ALT:break;default:clearTimeout(a.searching);a.searching=setTimeout(function(){a.search(null,c)},a.options.delay);break}}).bind("focus.autocomplete",function(){a.selectedItem=null;a.previous=a.element.val()}).bind("blur.autocomplete",
function(c){clearTimeout(a.searching);a.closing=setTimeout(function(){a.close(c);a._change(c)},150)});this._initSource();this.response=function(){return a._response.apply(a,arguments)};this.menu=e("<ul></ul>").addClass("ui-autocomplete").appendTo("body",b).menu({focus:function(c,d){d=d.item.data("item.autocomplete");false!==a._trigger("focus",null,{item:d})&&/^key/.test(c.originalEvent.type)&&a.element.val(d.value)},selected:function(c,d){d=d.item.data("item.autocomplete");false!==a._trigger("select",
c,{item:d})&&a.element.val(d.value);a.close(c);c=a.previous;if(a.element[0]!==b.activeElement){a.element.focus();a.previous=c}a.selectedItem=d},blur:function(){a.menu.element.is(":visible")&&a.element.val(a.term)}}).zIndex(this.element.zIndex()+1).css({top:0,left:0}).hide().data("menu");e.fn.bgiframe&&this.menu.element.bgiframe()},destroy:function(){this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete").removeAttr("role").removeAttr("aria-autocomplete").removeAttr("aria-haspopup");
this.menu.element.remove();e.Widget.prototype.destroy.call(this)},_setOption:function(a){e.Widget.prototype._setOption.apply(this,arguments);a==="source"&&this._initSource()},_initSource:function(){var a,b;if(e.isArray(this.options.source)){a=this.options.source;this.source=function(c,d){d(e.ui.autocomplete.filter(a,c.term))}}else if(typeof this.options.source==="string"){b=this.options.source;this.source=function(c,d){e.getJSON(b,c,d)}}else this.source=this.options.source},search:function(a,b){a=
a!=null?a:this.element.val();if(a.length<this.options.minLength)return this.close(b);clearTimeout(this.closing);if(this._trigger("search")!==false)return this._search(a)},_search:function(a){this.term=this.element.addClass("ui-autocomplete-loading").val();this.source({term:a},this.response)},_response:function(a){if(a.length){a=this._normalize(a);this._suggest(a);this._trigger("open")}else this.close();this.element.removeClass("ui-autocomplete-loading")},close:function(a){clearTimeout(this.closing);
if(this.menu.element.is(":visible")){this._trigger("close",a);this.menu.element.hide();this.menu.deactivate()}},_change:function(a){this.previous!==this.element.val()&&this._trigger("change",a,{item:this.selectedItem})},_normalize:function(a){if(a.length&&a[0].label&&a[0].value)return a;return e.map(a,function(b){if(typeof b==="string")return{label:b,value:b};return e.extend({label:b.label||b.value,value:b.value||b.label},b)})},_suggest:function(a){var b=this.menu.element.empty().zIndex(this.element.zIndex()+
1),c;this._renderMenu(b,a);this.menu.deactivate();this.menu.refresh();this.menu.element.show().position({my:"left top",at:"left bottom",of:this.element,collision:"none"});a=b.width("").width();c=this.element.width();b.width(Math.max(a,c))},_renderMenu:function(a,b){var c=this;e.each(b,function(d,f){c._renderItem(a,f)})},_renderItem:function(a,b){return e("<li></li>").data("item.autocomplete",b).append("<a>"+b.label+"</a>").appendTo(a)},_move:function(a,b){if(this.menu.element.is(":visible"))if(this.menu.first()&&
/^previous/.test(a)||this.menu.last()&&/^next/.test(a)){this.element.val(this.term);this.menu.deactivate()}else this.menu[a](b);else this.search(null,b)},widget:function(){return this.menu.element}});e.extend(e.ui.autocomplete,{escapeRegex:function(a){return a.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi,"\\$1")},filter:function(a,b){var c=new RegExp(e.ui.autocomplete.escapeRegex(b),"i");return e.grep(a,function(d){return c.test(d.label||d.value||d)})}})})(jQuery);
(function(e){e.widget("ui.menu",{_create:function(){var a=this;this.element.addClass("ui-menu ui-widget ui-widget-content ui-corner-all").attr({role:"listbox","aria-activedescendant":"ui-active-menuitem"}).click(function(b){if(e(b.target).closest(".ui-menu-item a").length){b.preventDefault();a.select(b)}});this.refresh()},refresh:function(){var a=this;this.element.children("li:not(.ui-menu-item):has(a)").addClass("ui-menu-item").attr("role","menuitem").children("a").addClass("ui-corner-all").attr("tabindex",
-1).mouseenter(function(b){a.activate(b,e(this).parent())}).mouseleave(function(){a.deactivate()})},activate:function(a,b){this.deactivate();if(this.hasScroll()){var c=b.offset().top-this.element.offset().top,d=this.element.attr("scrollTop"),f=this.element.height();if(c<0)this.element.attr("scrollTop",d+c);else c>f&&this.element.attr("scrollTop",d+c-f+b.height())}this.active=b.eq(0).children("a").addClass("ui-state-hover").attr("id","ui-active-menuitem").end();this._trigger("focus",a,{item:b})},deactivate:function(){if(this.active){this.active.children("a").removeClass("ui-state-hover").removeAttr("id");
this._trigger("blur");this.active=null}},next:function(a){this.move("next",".ui-menu-item:first",a)},previous:function(a){this.move("prev",".ui-menu-item:last",a)},first:function(){return this.active&&!this.active.prev().length},last:function(){return this.active&&!this.active.next().length},move:function(a,b,c){if(this.active){a=this.active[a+"All"](".ui-menu-item").eq(0);a.length?this.activate(c,a):this.activate(c,this.element.children(b))}else this.activate(c,this.element.children(b))},nextPage:function(a){if(this.hasScroll())if(!this.active||
this.last())this.activate(a,this.element.children(":first"));else{var b=this.active.offset().top,c=this.element.height(),d=this.element.children("li").filter(function(){var f=e(this).offset().top-b-c+e(this).height();return f<10&&f>-10});d.length||(d=this.element.children(":last"));this.activate(a,d)}else this.activate(a,this.element.children(!this.active||this.last()?":first":":last"))},previousPage:function(a){if(this.hasScroll())if(!this.active||this.first())this.activate(a,this.element.children(":last"));
else{var b=this.active.offset().top,c=this.element.height();result=this.element.children("li").filter(function(){var d=e(this).offset().top-b+c-e(this).height();return d<10&&d>-10});result.length||(result=this.element.children(":first"));this.activate(a,result)}else this.activate(a,this.element.children(!this.active||this.first()?":last":":first"))},hasScroll:function(){return this.element.height()<this.element.attr("scrollHeight")},select:function(a){this._trigger("selected",a,{item:this.active})}})})(jQuery);
(function(a){var g,i=function(b){a(":ui-button",b.target.form).each(function(){var c=a(this).data("button");setTimeout(function(){c.refresh()},1)})},h=function(b){var c=b.name,d=b.form,e=a([]);if(c)e=d?a(d).find("[name='"+c+"']"):a("[name='"+c+"']",b.ownerDocument).filter(function(){return!this.form});return e};a.widget("ui.button",{options:{text:true,label:null,icons:{primary:null,secondary:null}},_create:function(){this.element.closest("form").unbind("reset.button").bind("reset.button",i);this._determineButtonType();
this.hasTitle=!!this.buttonElement.attr("title");var b=this,c=this.options,d=this.type==="checkbox"||this.type==="radio",e="ui-state-hover"+(!d?" ui-state-active":"");if(c.label===null)c.label=this.buttonElement.html();if(this.element.is(":disabled"))c.disabled=true;this.buttonElement.addClass("ui-button ui-widget ui-state-default ui-corner-all").attr("role","button").bind("mouseenter.button",function(){if(!c.disabled){a(this).addClass("ui-state-hover");this===g&&a(this).addClass("ui-state-active")}}).bind("mouseleave.button",
function(){c.disabled||a(this).removeClass(e)}).bind("focus.button",function(){a(this).addClass("ui-state-focus")}).bind("blur.button",function(){a(this).removeClass("ui-state-focus")});d&&this.element.bind("change.button",function(){b.refresh()});if(this.type==="checkbox")this.buttonElement.bind("click.button",function(){if(c.disabled)return false;a(this).toggleClass("ui-state-active");b.buttonElement.attr("aria-pressed",b.element[0].checked)});else if(this.type==="radio")this.buttonElement.bind("click.button",
function(){if(c.disabled)return false;a(this).addClass("ui-state-active");b.buttonElement.attr("aria-pressed",true);var f=b.element[0];h(f).not(f).map(function(){return a(this).button("widget")[0]}).removeClass("ui-state-active").attr("aria-pressed",false)});else{this.buttonElement.bind("mousedown.button",function(){if(c.disabled)return false;a(this).addClass("ui-state-active");g=this;a(document).one("mouseup",function(){g=null})}).bind("mouseup.button",function(){if(c.disabled)return false;a(this).removeClass("ui-state-active")}).bind("keydown.button",
function(f){if(c.disabled)return false;if(f.keyCode==a.ui.keyCode.SPACE||f.keyCode==a.ui.keyCode.ENTER)a(this).addClass("ui-state-active")}).bind("keyup.button",function(){a(this).removeClass("ui-state-active")});this.buttonElement.is("a")&&this.buttonElement.keyup(function(f){f.keyCode===a.ui.keyCode.SPACE&&a(this).click()})}this._setOption("disabled",c.disabled)},_determineButtonType:function(){this.type=this.element.is(":checkbox")?"checkbox":this.element.is(":radio")?"radio":this.element.is("input")?
"input":"button";if(this.type==="checkbox"||this.type==="radio"){this.buttonElement=this.element.parents().last().find("[for="+this.element.attr("id")+"]");this.element.addClass("ui-helper-hidden-accessible");var b=this.element.is(":checked");b&&this.buttonElement.addClass("ui-state-active");this.buttonElement.attr("aria-pressed",b)}else this.buttonElement=this.element},widget:function(){return this.buttonElement},destroy:function(){this.element.removeClass("ui-helper-hidden-accessible");this.buttonElement.removeClass("ui-button ui-widget ui-state-default ui-corner-all ui-state-hover ui-state-active ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon ui-button-text-only").removeAttr("role").removeAttr("aria-pressed").html(this.buttonElement.find(".ui-button-text").html());
this.hasTitle||this.buttonElement.removeAttr("title");a.Widget.prototype.destroy.call(this)},_setOption:function(b,c){a.Widget.prototype._setOption.apply(this,arguments);if(b==="disabled")c?this.element.attr("disabled",true):this.element.removeAttr("disabled");this._resetButton()},refresh:function(){var b=this.element.is(":disabled");b!==this.options.disabled&&this._setOption("disabled",b);if(this.type==="radio")h(this.element[0]).each(function(){a(this).is(":checked")?a(this).button("widget").addClass("ui-state-active").attr("aria-pressed",
true):a(this).button("widget").removeClass("ui-state-active").attr("aria-pressed",false)});else if(this.type==="checkbox")this.element.is(":checked")?this.buttonElement.addClass("ui-state-active").attr("aria-pressed",true):this.buttonElement.removeClass("ui-state-active").attr("aria-pressed",false)},_resetButton:function(){if(this.type==="input")this.options.label&&this.element.val(this.options.label);else{var b=this.buttonElement,c=a("<span></span>").addClass("ui-button-text").html(this.options.label).appendTo(b.empty()).text(),
d=this.options.icons,e=d.primary&&d.secondary;if(d.primary||d.secondary){b.addClass("ui-button-text-icon"+(e?"s":""));d.primary&&b.prepend("<span class='ui-button-icon-primary ui-icon "+d.primary+"'></span>");d.secondary&&b.append("<span class='ui-button-icon-secondary ui-icon "+d.secondary+"'></span>");if(!this.options.text){b.addClass(e?"ui-button-icons-only":"ui-button-icon-only").removeClass("ui-button-text-icons ui-button-text-icon");this.hasTitle||b.attr("title",c)}}else b.addClass("ui-button-text-only")}}});
a.widget("ui.buttonset",{_create:function(){this.element.addClass("ui-buttonset");this._init()},_init:function(){this.refresh()},_setOption:function(b,c){b==="disabled"&&this.buttons.button("option",b,c);a.Widget.prototype._setOption.apply(this,arguments)},refresh:function(){this.buttons=this.element.find(":button, :submit, :reset, :checkbox, :radio, a, :data(button)").filter(":ui-button").button("refresh").end().not(":ui-button").button().end().map(function(){return a(this).button("widget")[0]}).removeClass("ui-corner-all ui-corner-left ui-corner-right").filter(":first").addClass("ui-corner-left").end().filter(":last").addClass("ui-corner-right").end().end()},
destroy:function(){this.element.removeClass("ui-buttonset");this.buttons.map(function(){return a(this).button("widget")[0]}).removeClass("ui-corner-left ui-corner-right").end().button("destroy");a.Widget.prototype.destroy.call(this)}})})(jQuery);
(function(d){function J(){this.debug=false;this._curInst=null;this._keyEvent=false;this._disabledInputs=[];this._inDialog=this._datepickerShowing=false;this._mainDivId="ui-datepicker-div";this._inlineClass="ui-datepicker-inline";this._appendClass="ui-datepicker-append";this._triggerClass="ui-datepicker-trigger";this._dialogClass="ui-datepicker-dialog";this._disableClass="ui-datepicker-disabled";this._unselectableClass="ui-datepicker-unselectable";this._currentClass="ui-datepicker-current-day";this._dayOverClass=
"ui-datepicker-days-cell-over";this.regional=[];this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su",
"Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:false,showMonthAfterYear:false,yearSuffix:""};this._defaults={showOn:"focus",showAnim:"show",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:false,hideIfNoPrevNext:false,navigationAsDateFormat:false,gotoCurrent:false,changeMonth:false,changeYear:false,yearRange:"c-10:c+10",showOtherMonths:false,selectOtherMonths:false,showWeek:false,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",
minDate:null,maxDate:null,duration:"_default",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:true,showButtonPanel:false,autoSize:false};d.extend(this._defaults,this.regional[""]);this.dpDiv=d('<div id="'+this._mainDivId+'" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible"></div>')}function E(a,b){d.extend(a,
b);for(var c in b)if(b[c]==null||b[c]==undefined)a[c]=b[c];return a}d.extend(d.ui,{datepicker:{version:"1.8.1"}});var y=(new Date).getTime();d.extend(J.prototype,{markerClassName:"hasDatepicker",log:function(){this.debug&&console.log.apply("",arguments)},_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(a){E(this._defaults,a||{});return this},_attachDatepicker:function(a,b){var c=null;for(var e in this._defaults){var f=a.getAttribute("date:"+e);if(f){c=c||{};try{c[e]=eval(f)}catch(h){c[e]=
f}}}e=a.nodeName.toLowerCase();f=e=="div"||e=="span";if(!a.id)a.id="dp"+ ++this.uuid;var i=this._newInst(d(a),f);i.settings=d.extend({},b||{},c||{});if(e=="input")this._connectDatepicker(a,i);else f&&this._inlineDatepicker(a,i)},_newInst:function(a,b){return{id:a[0].id.replace(/([^A-Za-z0-9_])/g,"\\\\$1"),input:a,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:b,dpDiv:!b?this.dpDiv:d('<div class="'+this._inlineClass+' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>')}},
_connectDatepicker:function(a,b){var c=d(a);b.append=d([]);b.trigger=d([]);if(!c.hasClass(this.markerClassName)){this._attachments(c,b);c.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp).bind("setData.datepicker",function(e,f,h){b.settings[f]=h}).bind("getData.datepicker",function(e,f){return this._get(b,f)});this._autoSize(b);d.data(a,"datepicker",b)}},_attachments:function(a,b){var c=this._get(b,"appendText"),e=this._get(b,"isRTL");b.append&&
b.append.remove();if(c){b.append=d('<span class="'+this._appendClass+'">'+c+"</span>");a[e?"before":"after"](b.append)}a.unbind("focus",this._showDatepicker);b.trigger&&b.trigger.remove();c=this._get(b,"showOn");if(c=="focus"||c=="both")a.focus(this._showDatepicker);if(c=="button"||c=="both"){c=this._get(b,"buttonText");var f=this._get(b,"buttonImage");b.trigger=d(this._get(b,"buttonImageOnly")?d("<img/>").addClass(this._triggerClass).attr({src:f,alt:c,title:c}):d('<button type="button"></button>').addClass(this._triggerClass).html(f==
""?c:d("<img/>").attr({src:f,alt:c,title:c})));a[e?"before":"after"](b.trigger);b.trigger.click(function(){d.datepicker._datepickerShowing&&d.datepicker._lastInput==a[0]?d.datepicker._hideDatepicker():d.datepicker._showDatepicker(a[0]);return false})}},_autoSize:function(a){if(this._get(a,"autoSize")&&!a.inline){var b=new Date(2009,11,20),c=this._get(a,"dateFormat");if(c.match(/[DM]/)){var e=function(f){for(var h=0,i=0,g=0;g<f.length;g++)if(f[g].length>h){h=f[g].length;i=g}return i};b.setMonth(e(this._get(a,
c.match(/MM/)?"monthNames":"monthNamesShort")));b.setDate(e(this._get(a,c.match(/DD/)?"dayNames":"dayNamesShort"))+20-b.getDay())}a.input.attr("size",this._formatDate(a,b).length)}},_inlineDatepicker:function(a,b){var c=d(a);if(!c.hasClass(this.markerClassName)){c.addClass(this.markerClassName).append(b.dpDiv).bind("setData.datepicker",function(e,f,h){b.settings[f]=h}).bind("getData.datepicker",function(e,f){return this._get(b,f)});d.data(a,"datepicker",b);this._setDate(b,this._getDefaultDate(b),
true);this._updateDatepicker(b);this._updateAlternate(b)}},_dialogDatepicker:function(a,b,c,e,f){a=this._dialogInst;if(!a){a="dp"+ ++this.uuid;this._dialogInput=d('<input type="text" id="'+a+'" style="position: absolute; top: -100px; width: 0px; z-index: -10;"/>');this._dialogInput.keydown(this._doKeyDown);d("body").append(this._dialogInput);a=this._dialogInst=this._newInst(this._dialogInput,false);a.settings={};d.data(this._dialogInput[0],"datepicker",a)}E(a.settings,e||{});b=b&&b.constructor==Date?
this._formatDate(a,b):b;this._dialogInput.val(b);this._pos=f?f.length?f:[f.pageX,f.pageY]:null;if(!this._pos)this._pos=[document.documentElement.clientWidth/2-100+(document.documentElement.scrollLeft||document.body.scrollLeft),document.documentElement.clientHeight/2-150+(document.documentElement.scrollTop||document.body.scrollTop)];this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px");a.settings.onSelect=c;this._inDialog=true;this.dpDiv.addClass(this._dialogClass);this._showDatepicker(this._dialogInput[0]);
d.blockUI&&d.blockUI(this.dpDiv);d.data(this._dialogInput[0],"datepicker",a);return this},_destroyDatepicker:function(a){var b=d(a),c=d.data(a,"datepicker");if(b.hasClass(this.markerClassName)){var e=a.nodeName.toLowerCase();d.removeData(a,"datepicker");if(e=="input"){c.append.remove();c.trigger.remove();b.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp)}else if(e=="div"||e=="span")b.removeClass(this.markerClassName).empty()}},
_enableDatepicker:function(a){var b=d(a),c=d.data(a,"datepicker");if(b.hasClass(this.markerClassName)){var e=a.nodeName.toLowerCase();if(e=="input"){a.disabled=false;c.trigger.filter("button").each(function(){this.disabled=false}).end().filter("img").css({opacity:"1.0",cursor:""})}else if(e=="div"||e=="span")b.children("."+this._inlineClass).children().removeClass("ui-state-disabled");this._disabledInputs=d.map(this._disabledInputs,function(f){return f==a?null:f})}},_disableDatepicker:function(a){var b=
d(a),c=d.data(a,"datepicker");if(b.hasClass(this.markerClassName)){var e=a.nodeName.toLowerCase();if(e=="input"){a.disabled=true;c.trigger.filter("button").each(function(){this.disabled=true}).end().filter("img").css({opacity:"0.5",cursor:"default"})}else if(e=="div"||e=="span")b.children("."+this._inlineClass).children().addClass("ui-state-disabled");this._disabledInputs=d.map(this._disabledInputs,function(f){return f==a?null:f});this._disabledInputs[this._disabledInputs.length]=a}},_isDisabledDatepicker:function(a){if(!a)return false;
for(var b=0;b<this._disabledInputs.length;b++)if(this._disabledInputs[b]==a)return true;return false},_getInst:function(a){try{return d.data(a,"datepicker")}catch(b){throw"Missing instance data for this datepicker";}},_optionDatepicker:function(a,b,c){var e=this._getInst(a);if(arguments.length==2&&typeof b=="string")return b=="defaults"?d.extend({},d.datepicker._defaults):e?b=="all"?d.extend({},e.settings):this._get(e,b):null;var f=b||{};if(typeof b=="string"){f={};f[b]=c}if(e){this._curInst==e&&
this._hideDatepicker();var h=this._getDateDatepicker(a,true);E(e.settings,f);this._attachments(d(a),e);this._autoSize(e);this._setDateDatepicker(a,h);this._updateDatepicker(e)}},_changeDatepicker:function(a,b,c){this._optionDatepicker(a,b,c)},_refreshDatepicker:function(a){(a=this._getInst(a))&&this._updateDatepicker(a)},_setDateDatepicker:function(a,b){if(a=this._getInst(a)){this._setDate(a,b);this._updateDatepicker(a);this._updateAlternate(a)}},_getDateDatepicker:function(a,b){(a=this._getInst(a))&&
!a.inline&&this._setDateFromField(a,b);return a?this._getDate(a):null},_doKeyDown:function(a){var b=d.datepicker._getInst(a.target),c=true,e=b.dpDiv.is(".ui-datepicker-rtl");b._keyEvent=true;if(d.datepicker._datepickerShowing)switch(a.keyCode){case 9:d.datepicker._hideDatepicker();c=false;break;case 13:c=d("td."+d.datepicker._dayOverClass,b.dpDiv).add(d("td."+d.datepicker._currentClass,b.dpDiv));c[0]?d.datepicker._selectDay(a.target,b.selectedMonth,b.selectedYear,c[0]):d.datepicker._hideDatepicker();
return false;case 27:d.datepicker._hideDatepicker();break;case 33:d.datepicker._adjustDate(a.target,a.ctrlKey?-d.datepicker._get(b,"stepBigMonths"):-d.datepicker._get(b,"stepMonths"),"M");break;case 34:d.datepicker._adjustDate(a.target,a.ctrlKey?+d.datepicker._get(b,"stepBigMonths"):+d.datepicker._get(b,"stepMonths"),"M");break;case 35:if(a.ctrlKey||a.metaKey)d.datepicker._clearDate(a.target);c=a.ctrlKey||a.metaKey;break;case 36:if(a.ctrlKey||a.metaKey)d.datepicker._gotoToday(a.target);c=a.ctrlKey||
a.metaKey;break;case 37:if(a.ctrlKey||a.metaKey)d.datepicker._adjustDate(a.target,e?+1:-1,"D");c=a.ctrlKey||a.metaKey;if(a.originalEvent.altKey)d.datepicker._adjustDate(a.target,a.ctrlKey?-d.datepicker._get(b,"stepBigMonths"):-d.datepicker._get(b,"stepMonths"),"M");break;case 38:if(a.ctrlKey||a.metaKey)d.datepicker._adjustDate(a.target,-7,"D");c=a.ctrlKey||a.metaKey;break;case 39:if(a.ctrlKey||a.metaKey)d.datepicker._adjustDate(a.target,e?-1:+1,"D");c=a.ctrlKey||a.metaKey;if(a.originalEvent.altKey)d.datepicker._adjustDate(a.target,
a.ctrlKey?+d.datepicker._get(b,"stepBigMonths"):+d.datepicker._get(b,"stepMonths"),"M");break;case 40:if(a.ctrlKey||a.metaKey)d.datepicker._adjustDate(a.target,+7,"D");c=a.ctrlKey||a.metaKey;break;default:c=false}else if(a.keyCode==36&&a.ctrlKey)d.datepicker._showDatepicker(this);else c=false;if(c){a.preventDefault();a.stopPropagation()}},_doKeyPress:function(a){var b=d.datepicker._getInst(a.target);if(d.datepicker._get(b,"constrainInput")){b=d.datepicker._possibleChars(d.datepicker._get(b,"dateFormat"));
var c=String.fromCharCode(a.charCode==undefined?a.keyCode:a.charCode);return a.ctrlKey||c<" "||!b||b.indexOf(c)>-1}},_doKeyUp:function(a){a=d.datepicker._getInst(a.target);if(a.input.val()!=a.lastVal)try{if(d.datepicker.parseDate(d.datepicker._get(a,"dateFormat"),a.input?a.input.val():null,d.datepicker._getFormatConfig(a))){d.datepicker._setDateFromField(a);d.datepicker._updateAlternate(a);d.datepicker._updateDatepicker(a)}}catch(b){d.datepicker.log(b)}return true},_showDatepicker:function(a){a=a.target||
a;if(a.nodeName.toLowerCase()!="input")a=d("input",a.parentNode)[0];if(!(d.datepicker._isDisabledDatepicker(a)||d.datepicker._lastInput==a)){var b=d.datepicker._getInst(a);d.datepicker._curInst&&d.datepicker._curInst!=b&&d.datepicker._curInst.dpDiv.stop(true,true);var c=d.datepicker._get(b,"beforeShow");E(b.settings,c?c.apply(a,[a,b]):{});b.lastVal=null;d.datepicker._lastInput=a;d.datepicker._setDateFromField(b);if(d.datepicker._inDialog)a.value="";if(!d.datepicker._pos){d.datepicker._pos=d.datepicker._findPos(a);
d.datepicker._pos[1]+=a.offsetHeight}var e=false;d(a).parents().each(function(){e|=d(this).css("position")=="fixed";return!e});if(e&&d.browser.opera){d.datepicker._pos[0]-=document.documentElement.scrollLeft;d.datepicker._pos[1]-=document.documentElement.scrollTop}c={left:d.datepicker._pos[0],top:d.datepicker._pos[1]};d.datepicker._pos=null;b.dpDiv.css({position:"absolute",display:"block",top:"-1000px"});d.datepicker._updateDatepicker(b);c=d.datepicker._checkOffset(b,c,e);b.dpDiv.css({position:d.datepicker._inDialog&&
d.blockUI?"static":e?"fixed":"absolute",display:"none",left:c.left+"px",top:c.top+"px"});if(!b.inline){c=d.datepicker._get(b,"showAnim");var f=d.datepicker._get(b,"duration"),h=function(){d.datepicker._datepickerShowing=true;var i=d.datepicker._getBorders(b.dpDiv);b.dpDiv.find("iframe.ui-datepicker-cover").css({left:-i[0],top:-i[1],width:b.dpDiv.outerWidth(),height:b.dpDiv.outerHeight()})};b.dpDiv.zIndex(d(a).zIndex()+1);d.effects&&d.effects[c]?b.dpDiv.show(c,d.datepicker._get(b,"showOptions"),f,
h):b.dpDiv[c||"show"](c?f:null,h);if(!c||!f)h();b.input.is(":visible")&&!b.input.is(":disabled")&&b.input.focus();d.datepicker._curInst=b}}},_updateDatepicker:function(a){var b=this,c=d.datepicker._getBorders(a.dpDiv);a.dpDiv.empty().append(this._generateHTML(a)).find("iframe.ui-datepicker-cover").css({left:-c[0],top:-c[1],width:a.dpDiv.outerWidth(),height:a.dpDiv.outerHeight()}).end().find("button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a").bind("mouseout",function(){d(this).removeClass("ui-state-hover");
this.className.indexOf("ui-datepicker-prev")!=-1&&d(this).removeClass("ui-datepicker-prev-hover");this.className.indexOf("ui-datepicker-next")!=-1&&d(this).removeClass("ui-datepicker-next-hover")}).bind("mouseover",function(){if(!b._isDisabledDatepicker(a.inline?a.dpDiv.parent()[0]:a.input[0])){d(this).parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover");d(this).addClass("ui-state-hover");this.className.indexOf("ui-datepicker-prev")!=-1&&d(this).addClass("ui-datepicker-prev-hover");
this.className.indexOf("ui-datepicker-next")!=-1&&d(this).addClass("ui-datepicker-next-hover")}}).end().find("."+this._dayOverClass+" a").trigger("mouseover").end();c=this._getNumberOfMonths(a);var e=c[1];e>1?a.dpDiv.addClass("ui-datepicker-multi-"+e).css("width",17*e+"em"):a.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width("");a.dpDiv[(c[0]!=1||c[1]!=1?"add":"remove")+"Class"]("ui-datepicker-multi");a.dpDiv[(this._get(a,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl");
a==d.datepicker._curInst&&d.datepicker._datepickerShowing&&a.input&&a.input.is(":visible")&&!a.input.is(":disabled")&&a.input.focus()},_getBorders:function(a){var b=function(c){return{thin:1,medium:2,thick:3}[c]||c};return[parseFloat(b(a.css("border-left-width"))),parseFloat(b(a.css("border-top-width")))]},_checkOffset:function(a,b,c){var e=a.dpDiv.outerWidth(),f=a.dpDiv.outerHeight(),h=a.input?a.input.outerWidth():0,i=a.input?a.input.outerHeight():0,g=document.documentElement.clientWidth+d(document).scrollLeft(),
k=document.documentElement.clientHeight+d(document).scrollTop();b.left-=this._get(a,"isRTL")?e-h:0;b.left-=c&&b.left==a.input.offset().left?d(document).scrollLeft():0;b.top-=c&&b.top==a.input.offset().top+i?d(document).scrollTop():0;b.left-=Math.min(b.left,b.left+e>g&&g>e?Math.abs(b.left+e-g):0);b.top-=Math.min(b.top,b.top+f>k&&k>f?Math.abs(f+i):0);return b},_findPos:function(a){for(var b=this._get(this._getInst(a),"isRTL");a&&(a.type=="hidden"||a.nodeType!=1);)a=a[b?"previousSibling":"nextSibling"];
a=d(a).offset();return[a.left,a.top]},_hideDatepicker:function(a){var b=this._curInst;if(!(!b||a&&b!=d.data(a,"datepicker")))if(this._datepickerShowing){a=this._get(b,"showAnim");var c=this._get(b,"duration"),e=function(){d.datepicker._tidyDialog(b);this._curInst=null};d.effects&&d.effects[a]?b.dpDiv.hide(a,d.datepicker._get(b,"showOptions"),c,e):b.dpDiv[a=="slideDown"?"slideUp":a=="fadeIn"?"fadeOut":"hide"](a?c:null,e);a||e();if(a=this._get(b,"onClose"))a.apply(b.input?b.input[0]:null,[b.input?b.input.val():
"",b]);this._datepickerShowing=false;this._lastInput=null;if(this._inDialog){this._dialogInput.css({position:"absolute",left:"0",top:"-100px"});if(d.blockUI){d.unblockUI();d("body").append(this.dpDiv)}}this._inDialog=false}},_tidyDialog:function(a){a.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(a){if(d.datepicker._curInst){a=d(a.target);a[0].id!=d.datepicker._mainDivId&&a.parents("#"+d.datepicker._mainDivId).length==0&&!a.hasClass(d.datepicker.markerClassName)&&
!a.hasClass(d.datepicker._triggerClass)&&d.datepicker._datepickerShowing&&!(d.datepicker._inDialog&&d.blockUI)&&d.datepicker._hideDatepicker()}},_adjustDate:function(a,b,c){a=d(a);var e=this._getInst(a[0]);if(!this._isDisabledDatepicker(a[0])){this._adjustInstDate(e,b+(c=="M"?this._get(e,"showCurrentAtPos"):0),c);this._updateDatepicker(e)}},_gotoToday:function(a){a=d(a);var b=this._getInst(a[0]);if(this._get(b,"gotoCurrent")&&b.currentDay){b.selectedDay=b.currentDay;b.drawMonth=b.selectedMonth=b.currentMonth;
b.drawYear=b.selectedYear=b.currentYear}else{var c=new Date;b.selectedDay=c.getDate();b.drawMonth=b.selectedMonth=c.getMonth();b.drawYear=b.selectedYear=c.getFullYear()}this._notifyChange(b);this._adjustDate(a)},_selectMonthYear:function(a,b,c){a=d(a);var e=this._getInst(a[0]);e._selectingMonthYear=false;e["selected"+(c=="M"?"Month":"Year")]=e["draw"+(c=="M"?"Month":"Year")]=parseInt(b.options[b.selectedIndex].value,10);this._notifyChange(e);this._adjustDate(a)},_clickMonthYear:function(a){a=this._getInst(d(a)[0]);
a.input&&a._selectingMonthYear&&!d.browser.msie&&a.input.focus();a._selectingMonthYear=!a._selectingMonthYear},_selectDay:function(a,b,c,e){var f=d(a);if(!(d(e).hasClass(this._unselectableClass)||this._isDisabledDatepicker(f[0]))){f=this._getInst(f[0]);f.selectedDay=f.currentDay=d("a",e).html();f.selectedMonth=f.currentMonth=b;f.selectedYear=f.currentYear=c;this._selectDate(a,this._formatDate(f,f.currentDay,f.currentMonth,f.currentYear))}},_clearDate:function(a){a=d(a);this._getInst(a[0]);this._selectDate(a,
"")},_selectDate:function(a,b){a=this._getInst(d(a)[0]);b=b!=null?b:this._formatDate(a);a.input&&a.input.val(b);this._updateAlternate(a);var c=this._get(a,"onSelect");if(c)c.apply(a.input?a.input[0]:null,[b,a]);else a.input&&a.input.trigger("change");if(a.inline)this._updateDatepicker(a);else{this._hideDatepicker();this._lastInput=a.input[0];typeof a.input[0]!="object"&&a.input.focus();this._lastInput=null}},_updateAlternate:function(a){var b=this._get(a,"altField");if(b){var c=this._get(a,"altFormat")||
this._get(a,"dateFormat"),e=this._getDate(a),f=this.formatDate(c,e,this._getFormatConfig(a));d(b).each(function(){d(this).val(f)})}},noWeekends:function(a){a=a.getDay();return[a>0&&a<6,""]},iso8601Week:function(a){a=new Date(a.getTime());a.setDate(a.getDate()+4-(a.getDay()||7));var b=a.getTime();a.setMonth(0);a.setDate(1);return Math.floor(Math.round((b-a)/864E5)/7)+1},parseDate:function(a,b,c){if(a==null||b==null)throw"Invalid arguments";b=typeof b=="object"?b.toString():b+"";if(b=="")return null;
for(var e=(c?c.shortYearCutoff:null)||this._defaults.shortYearCutoff,f=(c?c.dayNamesShort:null)||this._defaults.dayNamesShort,h=(c?c.dayNames:null)||this._defaults.dayNames,i=(c?c.monthNamesShort:null)||this._defaults.monthNamesShort,g=(c?c.monthNames:null)||this._defaults.monthNames,k=c=-1,l=-1,u=-1,j=false,o=function(p){(p=z+1<a.length&&a.charAt(z+1)==p)&&z++;return p},m=function(p){o(p);p=new RegExp("^\\d{1,"+(p=="@"?14:p=="!"?20:p=="y"?4:p=="o"?3:2)+"}");p=b.substring(s).match(p);if(!p)throw"Missing number at position "+
s;s+=p[0].length;return parseInt(p[0],10)},n=function(p,w,G){p=o(p)?G:w;for(w=0;w<p.length;w++)if(b.substr(s,p[w].length)==p[w]){s+=p[w].length;return w+1}throw"Unknown name at position "+s;},r=function(){if(b.charAt(s)!=a.charAt(z))throw"Unexpected literal at position "+s;s++},s=0,z=0;z<a.length;z++)if(j)if(a.charAt(z)=="'"&&!o("'"))j=false;else r();else switch(a.charAt(z)){case "d":l=m("d");break;case "D":n("D",f,h);break;case "o":u=m("o");break;case "m":k=m("m");break;case "M":k=n("M",i,g);break;
case "y":c=m("y");break;case "@":var v=new Date(m("@"));c=v.getFullYear();k=v.getMonth()+1;l=v.getDate();break;case "!":v=new Date((m("!")-this._ticksTo1970)/1E4);c=v.getFullYear();k=v.getMonth()+1;l=v.getDate();break;case "'":if(o("'"))r();else j=true;break;default:r()}if(c==-1)c=(new Date).getFullYear();else if(c<100)c+=(new Date).getFullYear()-(new Date).getFullYear()%100+(c<=e?0:-100);if(u>-1){k=1;l=u;do{e=this._getDaysInMonth(c,k-1);if(l<=e)break;k++;l-=e}while(1)}v=this._daylightSavingAdjust(new Date(c,
k-1,l));if(v.getFullYear()!=c||v.getMonth()+1!=k||v.getDate()!=l)throw"Invalid date";return v},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925))*24*60*60*1E7,formatDate:function(a,b,c){if(!b)return"";var e=(c?c.dayNamesShort:null)||this._defaults.dayNamesShort,f=(c?
c.dayNames:null)||this._defaults.dayNames,h=(c?c.monthNamesShort:null)||this._defaults.monthNamesShort;c=(c?c.monthNames:null)||this._defaults.monthNames;var i=function(o){(o=j+1<a.length&&a.charAt(j+1)==o)&&j++;return o},g=function(o,m,n){m=""+m;if(i(o))for(;m.length<n;)m="0"+m;return m},k=function(o,m,n,r){return i(o)?r[m]:n[m]},l="",u=false;if(b)for(var j=0;j<a.length;j++)if(u)if(a.charAt(j)=="'"&&!i("'"))u=false;else l+=a.charAt(j);else switch(a.charAt(j)){case "d":l+=g("d",b.getDate(),2);break;
case "D":l+=k("D",b.getDay(),e,f);break;case "o":l+=g("o",(b.getTime()-(new Date(b.getFullYear(),0,0)).getTime())/864E5,3);break;case "m":l+=g("m",b.getMonth()+1,2);break;case "M":l+=k("M",b.getMonth(),h,c);break;case "y":l+=i("y")?b.getFullYear():(b.getYear()%100<10?"0":"")+b.getYear()%100;break;case "@":l+=b.getTime();break;case "!":l+=b.getTime()*1E4+this._ticksTo1970;break;case "'":if(i("'"))l+="'";else u=true;break;default:l+=a.charAt(j)}return l},_possibleChars:function(a){for(var b="",c=false,
e=function(h){(h=f+1<a.length&&a.charAt(f+1)==h)&&f++;return h},f=0;f<a.length;f++)if(c)if(a.charAt(f)=="'"&&!e("'"))c=false;else b+=a.charAt(f);else switch(a.charAt(f)){case "d":case "m":case "y":case "@":b+="0123456789";break;case "D":case "M":return null;case "'":if(e("'"))b+="'";else c=true;break;default:b+=a.charAt(f)}return b},_get:function(a,b){return a.settings[b]!==undefined?a.settings[b]:this._defaults[b]},_setDateFromField:function(a,b){if(a.input.val()!=a.lastVal){var c=this._get(a,"dateFormat"),
e=a.lastVal=a.input?a.input.val():null,f,h;f=h=this._getDefaultDate(a);var i=this._getFormatConfig(a);try{f=this.parseDate(c,e,i)||h}catch(g){this.log(g);e=b?"":e}a.selectedDay=f.getDate();a.drawMonth=a.selectedMonth=f.getMonth();a.drawYear=a.selectedYear=f.getFullYear();a.currentDay=e?f.getDate():0;a.currentMonth=e?f.getMonth():0;a.currentYear=e?f.getFullYear():0;this._adjustInstDate(a)}},_getDefaultDate:function(a){return this._restrictMinMax(a,this._determineDate(a,this._get(a,"defaultDate"),new Date))},
_determineDate:function(a,b,c){var e=function(h){var i=new Date;i.setDate(i.getDate()+h);return i},f=function(h){try{return d.datepicker.parseDate(d.datepicker._get(a,"dateFormat"),h,d.datepicker._getFormatConfig(a))}catch(i){}var g=(h.toLowerCase().match(/^c/)?d.datepicker._getDate(a):null)||new Date,k=g.getFullYear(),l=g.getMonth();g=g.getDate();for(var u=/([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,j=u.exec(h);j;){switch(j[2]||"d"){case "d":case "D":g+=parseInt(j[1],10);break;case "w":case "W":g+=parseInt(j[1],
10)*7;break;case "m":case "M":l+=parseInt(j[1],10);g=Math.min(g,d.datepicker._getDaysInMonth(k,l));break;case "y":case "Y":k+=parseInt(j[1],10);g=Math.min(g,d.datepicker._getDaysInMonth(k,l));break}j=u.exec(h)}return new Date(k,l,g)};if(b=(b=b==null?c:typeof b=="string"?f(b):typeof b=="number"?isNaN(b)?c:e(b):b)&&b.toString()=="Invalid Date"?c:b){b.setHours(0);b.setMinutes(0);b.setSeconds(0);b.setMilliseconds(0)}return this._daylightSavingAdjust(b)},_daylightSavingAdjust:function(a){if(!a)return null;
a.setHours(a.getHours()>12?a.getHours()+2:0);return a},_setDate:function(a,b,c){var e=!b,f=a.selectedMonth,h=a.selectedYear;b=this._restrictMinMax(a,this._determineDate(a,b,new Date));a.selectedDay=a.currentDay=b.getDate();a.drawMonth=a.selectedMonth=a.currentMonth=b.getMonth();a.drawYear=a.selectedYear=a.currentYear=b.getFullYear();if((f!=a.selectedMonth||h!=a.selectedYear)&&!c)this._notifyChange(a);this._adjustInstDate(a);if(a.input)a.input.val(e?"":this._formatDate(a))},_getDate:function(a){return!a.currentYear||
a.input&&a.input.val()==""?null:this._daylightSavingAdjust(new Date(a.currentYear,a.currentMonth,a.currentDay))},_generateHTML:function(a){var b=new Date;b=this._daylightSavingAdjust(new Date(b.getFullYear(),b.getMonth(),b.getDate()));var c=this._get(a,"isRTL"),e=this._get(a,"showButtonPanel"),f=this._get(a,"hideIfNoPrevNext"),h=this._get(a,"navigationAsDateFormat"),i=this._getNumberOfMonths(a),g=this._get(a,"showCurrentAtPos"),k=this._get(a,"stepMonths"),l=i[0]!=1||i[1]!=1,u=this._daylightSavingAdjust(!a.currentDay?
new Date(9999,9,9):new Date(a.currentYear,a.currentMonth,a.currentDay)),j=this._getMinMaxDate(a,"min"),o=this._getMinMaxDate(a,"max");g=a.drawMonth-g;var m=a.drawYear;if(g<0){g+=12;m--}if(o){var n=this._daylightSavingAdjust(new Date(o.getFullYear(),o.getMonth()-i[0]*i[1]+1,o.getDate()));for(n=j&&n<j?j:n;this._daylightSavingAdjust(new Date(m,g,1))>n;){g--;if(g<0){g=11;m--}}}a.drawMonth=g;a.drawYear=m;n=this._get(a,"prevText");n=!h?n:this.formatDate(n,this._daylightSavingAdjust(new Date(m,g-k,1)),this._getFormatConfig(a));
n=this._canAdjustMonth(a,-1,m,g)?'<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery_'+y+".datepicker._adjustDate('#"+a.id+"', -"+k+", 'M');\" title=\""+n+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"e":"w")+'">'+n+"</span></a>":f?"":'<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+n+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"e":"w")+'">'+n+"</span></a>";var r=this._get(a,"nextText");r=!h?r:this.formatDate(r,this._daylightSavingAdjust(new Date(m,
g+k,1)),this._getFormatConfig(a));f=this._canAdjustMonth(a,+1,m,g)?'<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery_'+y+".datepicker._adjustDate('#"+a.id+"', +"+k+", 'M');\" title=\""+r+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"w":"e")+'">'+r+"</span></a>":f?"":'<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+r+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"w":"e")+'">'+r+"</span></a>";k=this._get(a,"currentText");r=this._get(a,"gotoCurrent")&&
a.currentDay?u:b;k=!h?k:this.formatDate(k,r,this._getFormatConfig(a));h=!a.inline?'<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery_'+y+'.datepicker._hideDatepicker();">'+this._get(a,"closeText")+"</button>":"";e=e?'<div class="ui-datepicker-buttonpane ui-widget-content">'+(c?h:"")+(this._isInRange(a,r)?'<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery_'+
y+".datepicker._gotoToday('#"+a.id+"');\">"+k+"</button>":"")+(c?"":h)+"</div>":"";h=parseInt(this._get(a,"firstDay"),10);h=isNaN(h)?0:h;k=this._get(a,"showWeek");r=this._get(a,"dayNames");this._get(a,"dayNamesShort");var s=this._get(a,"dayNamesMin"),z=this._get(a,"monthNames"),v=this._get(a,"monthNamesShort"),p=this._get(a,"beforeShowDay"),w=this._get(a,"showOtherMonths"),G=this._get(a,"selectOtherMonths");this._get(a,"calculateWeek");for(var K=this._getDefaultDate(a),H="",C=0;C<i[0];C++){for(var L=
"",D=0;D<i[1];D++){var M=this._daylightSavingAdjust(new Date(m,g,a.selectedDay)),t=" ui-corner-all",x="";if(l){x+='<div class="ui-datepicker-group';if(i[1]>1)switch(D){case 0:x+=" ui-datepicker-group-first";t=" ui-corner-"+(c?"right":"left");break;case i[1]-1:x+=" ui-datepicker-group-last";t=" ui-corner-"+(c?"left":"right");break;default:x+=" ui-datepicker-group-middle";t="";break}x+='">'}x+='<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix'+t+'">'+(/all|left/.test(t)&&C==0?c?
f:n:"")+(/all|right/.test(t)&&C==0?c?n:f:"")+this._generateMonthYearHeader(a,g,m,j,o,C>0||D>0,z,v)+'</div><table class="ui-datepicker-calendar"><thead><tr>';var A=k?'<th class="ui-datepicker-week-col">'+this._get(a,"weekHeader")+"</th>":"";for(t=0;t<7;t++){var q=(t+h)%7;A+="<th"+((t+h+6)%7>=5?' class="ui-datepicker-week-end"':"")+'><span title="'+r[q]+'">'+s[q]+"</span></th>"}x+=A+"</tr></thead><tbody>";A=this._getDaysInMonth(m,g);if(m==a.selectedYear&&g==a.selectedMonth)a.selectedDay=Math.min(a.selectedDay,
A);t=(this._getFirstDayOfMonth(m,g)-h+7)%7;A=l?6:Math.ceil((t+A)/7);q=this._daylightSavingAdjust(new Date(m,g,1-t));for(var N=0;N<A;N++){x+="<tr>";var O=!k?"":'<td class="ui-datepicker-week-col">'+this._get(a,"calculateWeek")(q)+"</td>";for(t=0;t<7;t++){var F=p?p.apply(a.input?a.input[0]:null,[q]):[true,""],B=q.getMonth()!=g,I=B&&!G||!F[0]||j&&q<j||o&&q>o;O+='<td class="'+((t+h+6)%7>=5?" ui-datepicker-week-end":"")+(B?" ui-datepicker-other-month":"")+(q.getTime()==M.getTime()&&g==a.selectedMonth&&
a._keyEvent||K.getTime()==q.getTime()&&K.getTime()==M.getTime()?" "+this._dayOverClass:"")+(I?" "+this._unselectableClass+" ui-state-disabled":"")+(B&&!w?"":" "+F[1]+(q.getTime()==u.getTime()?" "+this._currentClass:"")+(q.getTime()==b.getTime()?" ui-datepicker-today":""))+'"'+((!B||w)&&F[2]?' title="'+F[2]+'"':"")+(I?"":' onclick="DP_jQuery_'+y+".datepicker._selectDay('#"+a.id+"',"+q.getMonth()+","+q.getFullYear()+', this);return false;"')+">"+(B&&!w?"&#xa0;":I?'<span class="ui-state-default">'+q.getDate()+
"</span>":'<a class="ui-state-default'+(q.getTime()==b.getTime()?" ui-state-highlight":"")+(q.getTime()==u.getTime()?" ui-state-active":"")+(B?" ui-priority-secondary":"")+'" href="#">'+q.getDate()+"</a>")+"</td>";q.setDate(q.getDate()+1);q=this._daylightSavingAdjust(q)}x+=O+"</tr>"}g++;if(g>11){g=0;m++}x+="</tbody></table>"+(l?"</div>"+(i[0]>0&&D==i[1]-1?'<div class="ui-datepicker-row-break"></div>':""):"");L+=x}H+=L}H+=e+(d.browser.msie&&parseInt(d.browser.version,10)<7&&!a.inline?'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>':
"");a._keyEvent=false;return H},_generateMonthYearHeader:function(a,b,c,e,f,h,i,g){var k=this._get(a,"changeMonth"),l=this._get(a,"changeYear"),u=this._get(a,"showMonthAfterYear"),j='<div class="ui-datepicker-title">',o="";if(h||!k)o+='<span class="ui-datepicker-month">'+i[b]+"</span>";else{i=e&&e.getFullYear()==c;var m=f&&f.getFullYear()==c;o+='<select class="ui-datepicker-month" onchange="DP_jQuery_'+y+".datepicker._selectMonthYear('#"+a.id+"', this, 'M');\" onclick=\"DP_jQuery_"+y+".datepicker._clickMonthYear('#"+
a.id+"');\">";for(var n=0;n<12;n++)if((!i||n>=e.getMonth())&&(!m||n<=f.getMonth()))o+='<option value="'+n+'"'+(n==b?' selected="selected"':"")+">"+g[n]+"</option>";o+="</select>"}u||(j+=o+(h||!(k&&l)?"&#xa0;":""));if(h||!l)j+='<span class="ui-datepicker-year">'+c+"</span>";else{g=this._get(a,"yearRange").split(":");var r=(new Date).getFullYear();i=function(s){s=s.match(/c[+-].*/)?c+parseInt(s.substring(1),10):s.match(/[+-].*/)?r+parseInt(s,10):parseInt(s,10);return isNaN(s)?r:s};b=i(g[0]);g=Math.max(b,
i(g[1]||""));b=e?Math.max(b,e.getFullYear()):b;g=f?Math.min(g,f.getFullYear()):g;for(j+='<select class="ui-datepicker-year" onchange="DP_jQuery_'+y+".datepicker._selectMonthYear('#"+a.id+"', this, 'Y');\" onclick=\"DP_jQuery_"+y+".datepicker._clickMonthYear('#"+a.id+"');\">";b<=g;b++)j+='<option value="'+b+'"'+(b==c?' selected="selected"':"")+">"+b+"</option>";j+="</select>"}j+=this._get(a,"yearSuffix");if(u)j+=(h||!(k&&l)?"&#xa0;":"")+o;j+="</div>";return j},_adjustInstDate:function(a,b,c){var e=
a.drawYear+(c=="Y"?b:0),f=a.drawMonth+(c=="M"?b:0);b=Math.min(a.selectedDay,this._getDaysInMonth(e,f))+(c=="D"?b:0);e=this._restrictMinMax(a,this._daylightSavingAdjust(new Date(e,f,b)));a.selectedDay=e.getDate();a.drawMonth=a.selectedMonth=e.getMonth();a.drawYear=a.selectedYear=e.getFullYear();if(c=="M"||c=="Y")this._notifyChange(a)},_restrictMinMax:function(a,b){var c=this._getMinMaxDate(a,"min");a=this._getMinMaxDate(a,"max");b=c&&b<c?c:b;return b=a&&b>a?a:b},_notifyChange:function(a){var b=this._get(a,
"onChangeMonthYear");if(b)b.apply(a.input?a.input[0]:null,[a.selectedYear,a.selectedMonth+1,a])},_getNumberOfMonths:function(a){a=this._get(a,"numberOfMonths");return a==null?[1,1]:typeof a=="number"?[1,a]:a},_getMinMaxDate:function(a,b){return this._determineDate(a,this._get(a,b+"Date"),null)},_getDaysInMonth:function(a,b){return 32-(new Date(a,b,32)).getDate()},_getFirstDayOfMonth:function(a,b){return(new Date(a,b,1)).getDay()},_canAdjustMonth:function(a,b,c,e){var f=this._getNumberOfMonths(a);
c=this._daylightSavingAdjust(new Date(c,e+(b<0?b:f[0]*f[1]),1));b<0&&c.setDate(this._getDaysInMonth(c.getFullYear(),c.getMonth()));return this._isInRange(a,c)},_isInRange:function(a,b){var c=this._getMinMaxDate(a,"min");a=this._getMinMaxDate(a,"max");return(!c||b.getTime()>=c.getTime())&&(!a||b.getTime()<=a.getTime())},_getFormatConfig:function(a){var b=this._get(a,"shortYearCutoff");b=typeof b!="string"?b:(new Date).getFullYear()%100+parseInt(b,10);return{shortYearCutoff:b,dayNamesShort:this._get(a,
"dayNamesShort"),dayNames:this._get(a,"dayNames"),monthNamesShort:this._get(a,"monthNamesShort"),monthNames:this._get(a,"monthNames")}},_formatDate:function(a,b,c,e){if(!b){a.currentDay=a.selectedDay;a.currentMonth=a.selectedMonth;a.currentYear=a.selectedYear}b=b?typeof b=="object"?b:this._daylightSavingAdjust(new Date(e,c,b)):this._daylightSavingAdjust(new Date(a.currentYear,a.currentMonth,a.currentDay));return this.formatDate(this._get(a,"dateFormat"),b,this._getFormatConfig(a))}});d.fn.datepicker=
function(a){if(!d.datepicker.initialized){d(document).mousedown(d.datepicker._checkExternalClick).find("body").append(d.datepicker.dpDiv);d.datepicker.initialized=true}var b=Array.prototype.slice.call(arguments,1);if(typeof a=="string"&&(a=="isDisabled"||a=="getDate"||a=="widget"))return d.datepicker["_"+a+"Datepicker"].apply(d.datepicker,[this[0]].concat(b));if(a=="option"&&arguments.length==2&&typeof arguments[1]=="string")return d.datepicker["_"+a+"Datepicker"].apply(d.datepicker,[this[0]].concat(b));
return this.each(function(){typeof a=="string"?d.datepicker["_"+a+"Datepicker"].apply(d.datepicker,[this].concat(b)):d.datepicker._attachDatepicker(this,a)})};d.datepicker=new J;d.datepicker.initialized=false;d.datepicker.uuid=(new Date).getTime();d.datepicker.version="1.8.1";window["DP_jQuery_"+y]=d})(jQuery);
(function(c){c.widget("ui.dialog",{options:{autoOpen:true,buttons:{},closeOnEscape:true,closeText:"close",dialogClass:"",draggable:true,hide:null,height:"auto",maxHeight:false,maxWidth:false,minHeight:150,minWidth:150,modal:false,position:"center",resizable:true,show:null,stack:true,title:"",width:300,zIndex:1E3},_create:function(){this.originalTitle=this.element.attr("title");var a=this,b=a.options,d=b.title||a.originalTitle||"&#160;",e=c.ui.dialog.getTitleId(a.element),g=(a.uiDialog=c("<div></div>")).appendTo(document.body).hide().addClass("ui-dialog ui-widget ui-widget-content ui-corner-all "+
b.dialogClass).css({zIndex:b.zIndex}).attr("tabIndex",-1).css("outline",0).keydown(function(i){if(b.closeOnEscape&&i.keyCode&&i.keyCode===c.ui.keyCode.ESCAPE){a.close(i);i.preventDefault()}}).attr({role:"dialog","aria-labelledby":e}).mousedown(function(i){a.moveToTop(false,i)});a.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(g);var f=(a.uiDialogTitlebar=c("<div></div>")).addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(g),
h=c('<a href="#"></a>').addClass("ui-dialog-titlebar-close ui-corner-all").attr("role","button").hover(function(){h.addClass("ui-state-hover")},function(){h.removeClass("ui-state-hover")}).focus(function(){h.addClass("ui-state-focus")}).blur(function(){h.removeClass("ui-state-focus")}).click(function(i){a.close(i);return false}).appendTo(f);(a.uiDialogTitlebarCloseText=c("<span></span>")).addClass("ui-icon ui-icon-closethick").text(b.closeText).appendTo(h);c("<span></span>").addClass("ui-dialog-title").attr("id",
e).html(d).prependTo(f);if(c.isFunction(b.beforeclose)&&!c.isFunction(b.beforeClose))b.beforeClose=b.beforeclose;f.find("*").add(f).disableSelection();b.draggable&&c.fn.draggable&&a._makeDraggable();b.resizable&&c.fn.resizable&&a._makeResizable();a._createButtons(b.buttons);a._isOpen=false;c.fn.bgiframe&&g.bgiframe()},_init:function(){this.options.autoOpen&&this.open()},destroy:function(){var a=this;a.overlay&&a.overlay.destroy();a.uiDialog.hide();a.element.unbind(".dialog").removeData("dialog").removeClass("ui-dialog-content ui-widget-content").hide().appendTo("body");
a.uiDialog.remove();a.originalTitle&&a.element.attr("title",a.originalTitle);return a},widget:function(){return this.uiDialog},close:function(a){var b=this,d;if(false!==b._trigger("beforeClose",a)){b.overlay&&b.overlay.destroy();b.uiDialog.unbind("keypress.ui-dialog");b._isOpen=false;if(b.options.hide)b.uiDialog.hide(b.options.hide,function(){b._trigger("close",a)});else{b.uiDialog.hide();b._trigger("close",a)}c.ui.dialog.overlay.resize();if(b.options.modal){d=0;c(".ui-dialog").each(function(){if(this!==
b.uiDialog[0])d=Math.max(d,c(this).css("z-index"))});c.ui.dialog.maxZ=d}return b}},isOpen:function(){return this._isOpen},moveToTop:function(a,b){var d=this,e=d.options;if(e.modal&&!a||!e.stack&&!e.modal)return d._trigger("focus",b);if(e.zIndex>c.ui.dialog.maxZ)c.ui.dialog.maxZ=e.zIndex;if(d.overlay){c.ui.dialog.maxZ+=1;d.overlay.$el.css("z-index",c.ui.dialog.overlay.maxZ=c.ui.dialog.maxZ)}a={scrollTop:d.element.attr("scrollTop"),scrollLeft:d.element.attr("scrollLeft")};c.ui.dialog.maxZ+=1;d.uiDialog.css("z-index",
c.ui.dialog.maxZ);d.element.attr(a);d._trigger("focus",b);return d},open:function(){if(!this._isOpen){var a=this,b=a.options,d=a.uiDialog;a.overlay=b.modal?new c.ui.dialog.overlay(a):null;d.next().length&&d.appendTo("body");a._size();a._position(b.position);d.show(b.show);a.moveToTop(true);b.modal&&d.bind("keypress.ui-dialog",function(e){if(e.keyCode===c.ui.keyCode.TAB){var g=c(":tabbable",this),f=g.filter(":first");g=g.filter(":last");if(e.target===g[0]&&!e.shiftKey){f.focus(1);return false}else if(e.target===
f[0]&&e.shiftKey){g.focus(1);return false}}});c([]).add(d.find(".ui-dialog-content :tabbable:first")).add(d.find(".ui-dialog-buttonpane :tabbable:first")).add(d).filter(":first").focus();a._trigger("open");a._isOpen=true;return a}},_createButtons:function(a){var b=this,d=false,e=c("<div></div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix");b.uiDialog.find(".ui-dialog-buttonpane").remove();typeof a==="object"&&a!==null&&c.each(a,function(){return!(d=true)});if(d){c.each(a,
function(g,f){g=c('<button type="button"></button>').text(g).click(function(){f.apply(b.element[0],arguments)}).appendTo(e);c.fn.button&&g.button()});e.appendTo(b.uiDialog)}},_makeDraggable:function(){function a(f){return{position:f.position,offset:f.offset}}var b=this,d=b.options,e=c(document),g;b.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(f,h){g=d.height==="auto"?"auto":c(this).height();c(this).height(c(this).height()).addClass("ui-dialog-dragging");
b._trigger("dragStart",f,a(h))},drag:function(f,h){b._trigger("drag",f,a(h))},stop:function(f,h){d.position=[h.position.left-e.scrollLeft(),h.position.top-e.scrollTop()];c(this).removeClass("ui-dialog-dragging").height(g);b._trigger("dragStop",f,a(h));c.ui.dialog.overlay.resize()}})},_makeResizable:function(a){function b(f){return{originalPosition:f.originalPosition,originalSize:f.originalSize,position:f.position,size:f.size}}a=a===undefined?this.options.resizable:a;var d=this,e=d.options,g=d.uiDialog.css("position");
a=typeof a==="string"?a:"n,e,s,w,se,sw,ne,nw";d.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:d.element,maxWidth:e.maxWidth,maxHeight:e.maxHeight,minWidth:e.minWidth,minHeight:d._minHeight(),handles:a,start:function(f,h){c(this).addClass("ui-dialog-resizing");d._trigger("resizeStart",f,b(h))},resize:function(f,h){d._trigger("resize",f,b(h))},stop:function(f,h){c(this).removeClass("ui-dialog-resizing");e.height=c(this).height();e.width=c(this).width();d._trigger("resizeStop",
f,b(h));c.ui.dialog.overlay.resize()}}).css("position",g).find(".ui-resizable-se").addClass("ui-icon ui-icon-grip-diagonal-se")},_minHeight:function(){var a=this.options;return a.height==="auto"?a.minHeight:Math.min(a.minHeight,a.height)},_position:function(a){var b=[],d=[0,0];a=a||c.ui.dialog.prototype.options.position;if(typeof a==="string"||typeof a==="object"&&"0"in a){b=a.split?a.split(" "):[a[0],a[1]];if(b.length===1)b[1]=b[0];c.each(["left","top"],function(e,g){if(+b[e]===b[e]){d[e]=b[e];b[e]=
g}})}else if(typeof a==="object"){if("left"in a){b[0]="left";d[0]=a.left}else if("right"in a){b[0]="right";d[0]=-a.right}if("top"in a){b[1]="top";d[1]=a.top}else if("bottom"in a){b[1]="bottom";d[1]=-a.bottom}}(a=this.uiDialog.is(":visible"))||this.uiDialog.show();this.uiDialog.css({top:0,left:0}).position({my:b.join(" "),at:b.join(" "),offset:d.join(" "),of:window,collision:"fit",using:function(e){var g=c(this).css(e).offset().top;g<0&&c(this).css("top",e.top-g)}});a||this.uiDialog.hide()},_setOption:function(a,
b){var d=this,e=d.uiDialog,g=e.is(":data(resizable)"),f=false;switch(a){case "beforeclose":a="beforeClose";break;case "buttons":d._createButtons(b);break;case "closeText":d.uiDialogTitlebarCloseText.text(""+b);break;case "dialogClass":e.removeClass(d.options.dialogClass).addClass("ui-dialog ui-widget ui-widget-content ui-corner-all "+b);break;case "disabled":b?e.addClass("ui-dialog-disabled"):e.removeClass("ui-dialog-disabled");break;case "draggable":b?d._makeDraggable():e.draggable("destroy");break;
case "height":f=true;break;case "maxHeight":g&&e.resizable("option","maxHeight",b);f=true;break;case "maxWidth":g&&e.resizable("option","maxWidth",b);f=true;break;case "minHeight":g&&e.resizable("option","minHeight",b);f=true;break;case "minWidth":g&&e.resizable("option","minWidth",b);f=true;break;case "position":d._position(b);break;case "resizable":g&&!b&&e.resizable("destroy");g&&typeof b==="string"&&e.resizable("option","handles",b);!g&&b!==false&&d._makeResizable(b);break;case "title":c(".ui-dialog-title",
d.uiDialogTitlebar).html(""+(b||"&#160;"));break;case "width":f=true;break}c.Widget.prototype._setOption.apply(d,arguments);f&&d._size()},_size:function(){var a=this.options,b;this.element.css({width:"auto",minHeight:0,height:0});b=this.uiDialog.css({height:"auto",width:a.width}).height();this.element.css(a.height==="auto"?{minHeight:Math.max(a.minHeight-b,0),height:"auto"}:{minHeight:0,height:Math.max(a.height-b,0)}).show();this.uiDialog.is(":data(resizable)")&&this.uiDialog.resizable("option","minHeight",
this._minHeight())}});c.extend(c.ui.dialog,{version:"1.8.1",uuid:0,maxZ:0,getTitleId:function(a){a=a.attr("id");if(!a){this.uuid+=1;a=this.uuid}return"ui-dialog-title-"+a},overlay:function(a){this.$el=c.ui.dialog.overlay.create(a)}});c.extend(c.ui.dialog.overlay,{instances:[],oldInstances:[],maxZ:0,events:c.map("focus,mousedown,mouseup,keydown,keypress,click".split(","),function(a){return a+".dialog-overlay"}).join(" "),create:function(a){if(this.instances.length===0){setTimeout(function(){c.ui.dialog.overlay.instances.length&&
c(document).bind(c.ui.dialog.overlay.events,function(d){return c(d.target).zIndex()>=c.ui.dialog.overlay.maxZ})},1);c(document).bind("keydown.dialog-overlay",function(d){if(a.options.closeOnEscape&&d.keyCode&&d.keyCode===c.ui.keyCode.ESCAPE){a.close(d);d.preventDefault()}});c(window).bind("resize.dialog-overlay",c.ui.dialog.overlay.resize)}var b=(this.oldInstances.pop()||c("<div></div>").addClass("ui-widget-overlay")).appendTo(document.body).css({width:this.width(),height:this.height()});c.fn.bgiframe&&
b.bgiframe();this.instances.push(b);return b},destroy:function(a){this.oldInstances.push(this.instances.splice(c.inArray(a,this.instances),1)[0]);this.instances.length===0&&c([document,window]).unbind(".dialog-overlay");a.remove();var b=0;c.each(this.instances,function(){b=Math.max(b,this.css("z-index"))});this.maxZ=b},height:function(){var a,b;if(c.browser.msie&&c.browser.version<7){a=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight);b=Math.max(document.documentElement.offsetHeight,
document.body.offsetHeight);return a<b?c(window).height()+"px":a+"px"}else return c(document).height()+"px"},width:function(){var a,b;if(c.browser.msie&&c.browser.version<7){a=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth);b=Math.max(document.documentElement.offsetWidth,document.body.offsetWidth);return a<b?c(window).width()+"px":a+"px"}else return c(document).width()+"px"},resize:function(){var a=c([]);c.each(c.ui.dialog.overlay.instances,function(){a=a.add(this)});a.css({width:0,
height:0}).css({width:c.ui.dialog.overlay.width(),height:c.ui.dialog.overlay.height()})}});c.extend(c.ui.dialog.overlay.prototype,{destroy:function(){c.ui.dialog.overlay.destroy(this.$el)}})})(jQuery);
(function(c){c.ui=c.ui||{};var m=/left|center|right/,n=/top|center|bottom/,p=c.fn.position,q=c.fn.offset;c.fn.position=function(a){if(!a||!a.of)return p.apply(this,arguments);a=c.extend({},a);var b=c(a.of),d=(a.collision||"flip").split(" "),e=a.offset?a.offset.split(" "):[0,0],g,h,i;if(a.of.nodeType===9){g=b.width();h=b.height();i={top:0,left:0}}else if(a.of.scrollTo&&a.of.document){g=b.width();h=b.height();i={top:b.scrollTop(),left:b.scrollLeft()}}else if(a.of.preventDefault){a.at="left top";g=h=
0;i={top:a.of.pageY,left:a.of.pageX}}else{g=b.outerWidth();h=b.outerHeight();i=b.offset()}c.each(["my","at"],function(){var f=(a[this]||"").split(" ");if(f.length===1)f=m.test(f[0])?f.concat(["center"]):n.test(f[0])?["center"].concat(f):["center","center"];f[0]=m.test(f[0])?f[0]:"center";f[1]=n.test(f[1])?f[1]:"center";a[this]=f});if(d.length===1)d[1]=d[0];e[0]=parseInt(e[0],10)||0;if(e.length===1)e[1]=e[0];e[1]=parseInt(e[1],10)||0;if(a.at[0]==="right")i.left+=g;else if(a.at[0]==="center")i.left+=
g/2;if(a.at[1]==="bottom")i.top+=h;else if(a.at[1]==="center")i.top+=h/2;i.left+=e[0];i.top+=e[1];return this.each(function(){var f=c(this),k=f.outerWidth(),l=f.outerHeight(),j=c.extend({},i);if(a.my[0]==="right")j.left-=k;else if(a.my[0]==="center")j.left-=k/2;if(a.my[1]==="bottom")j.top-=l;else if(a.my[1]==="center")j.top-=l/2;j.left=parseInt(j.left);j.top=parseInt(j.top);c.each(["left","top"],function(o,r){c.ui.position[d[o]]&&c.ui.position[d[o]][r](j,{targetWidth:g,targetHeight:h,elemWidth:k,
elemHeight:l,offset:e,my:a.my,at:a.at})});c.fn.bgiframe&&f.bgiframe();f.offset(c.extend(j,{using:a.using}))})};c.ui.position={fit:{left:function(a,b){var d=c(window);b=a.left+b.elemWidth-d.width()-d.scrollLeft();a.left=b>0?a.left-b:Math.max(0,a.left)},top:function(a,b){var d=c(window);b=a.top+b.elemHeight-d.height()-d.scrollTop();a.top=b>0?a.top-b:Math.max(0,a.top)}},flip:{left:function(a,b){if(b.at[0]!=="center"){var d=c(window);d=a.left+b.elemWidth-d.width()-d.scrollLeft();var e=b.my[0]==="left"?
-b.elemWidth:b.my[0]==="right"?b.elemWidth:0,g=-2*b.offset[0];a.left+=a.left<0?e+b.targetWidth+g:d>0?e-b.targetWidth+g:0}},top:function(a,b){if(b.at[1]!=="center"){var d=c(window);d=a.top+b.elemHeight-d.height()-d.scrollTop();var e=b.my[1]==="top"?-b.elemHeight:b.my[1]==="bottom"?b.elemHeight:0,g=b.at[1]==="top"?b.targetHeight:-b.targetHeight,h=-2*b.offset[1];a.top+=a.top<0?e+b.targetHeight+h:d>0?e+g+h:0}}}};if(!c.offset.setOffset){c.offset.setOffset=function(a,b){if(/static/.test(c.curCSS(a,"position")))a.style.position=
"relative";var d=c(a),e=d.offset(),g=parseInt(c.curCSS(a,"top",true),10)||0,h=parseInt(c.curCSS(a,"left",true),10)||0;e={top:b.top-e.top+g,left:b.left-e.left+h};"using"in b?b.using.call(a,e):d.css(e)};c.fn.offset=function(a){var b=this[0];if(!b||!b.ownerDocument)return null;if(a)return this.each(function(){c.offset.setOffset(this,a)});return q.call(this)}}})(jQuery);
(function(b){b.widget("ui.progressbar",{options:{value:0},_create:function(){this.element.addClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").attr({role:"progressbar","aria-valuemin":this._valueMin(),"aria-valuemax":this._valueMax(),"aria-valuenow":this._value()});this.valueDiv=b("<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>").appendTo(this.element);this._refreshValue()},destroy:function(){this.element.removeClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow");
this.valueDiv.remove();b.Widget.prototype.destroy.apply(this,arguments)},value:function(a){if(a===undefined)return this._value();this._setOption("value",a);return this},_setOption:function(a,c){switch(a){case "value":this.options.value=c;this._refreshValue();this._trigger("change");break}b.Widget.prototype._setOption.apply(this,arguments)},_value:function(){var a=this.options.value;if(typeof a!=="number")a=0;if(a<this._valueMin())a=this._valueMin();if(a>this._valueMax())a=this._valueMax();return a},
_valueMin:function(){return 0},_valueMax:function(){return 100},_refreshValue:function(){var a=this.value();this.valueDiv[a===this._valueMax()?"addClass":"removeClass"]("ui-corner-right").width(a+"%");this.element.attr("aria-valuenow",a)}});b.extend(b.ui.progressbar,{version:"1.8.1"})})(jQuery);
(function(d){d.widget("ui.slider",d.ui.mouse,{widgetEventPrefix:"slide",options:{animate:false,distance:0,max:100,min:0,orientation:"horizontal",range:false,step:1,value:0,values:null},_create:function(){var b=this,a=this.options;this._mouseSliding=this._keySliding=false;this._animateOff=true;this._handleIndex=null;this._detectOrientation();this._mouseInit();this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget ui-widget-content ui-corner-all");a.disabled&&this.element.addClass("ui-slider-disabled ui-disabled");
this.range=d([]);if(a.range){if(a.range===true){this.range=d("<div></div>");if(!a.values)a.values=[this._valueMin(),this._valueMin()];if(a.values.length&&a.values.length!==2)a.values=[a.values[0],a.values[0]]}else this.range=d("<div></div>");this.range.appendTo(this.element).addClass("ui-slider-range");if(a.range==="min"||a.range==="max")this.range.addClass("ui-slider-range-"+a.range);this.range.addClass("ui-widget-header")}d(".ui-slider-handle",this.element).length===0&&d("<a href='#'></a>").appendTo(this.element).addClass("ui-slider-handle");
if(a.values&&a.values.length)for(;d(".ui-slider-handle",this.element).length<a.values.length;)d("<a href='#'></a>").appendTo(this.element).addClass("ui-slider-handle");this.handles=d(".ui-slider-handle",this.element).addClass("ui-state-default ui-corner-all");this.handle=this.handles.eq(0);this.handles.add(this.range).filter("a").click(function(c){c.preventDefault()}).hover(function(){a.disabled||d(this).addClass("ui-state-hover")},function(){d(this).removeClass("ui-state-hover")}).focus(function(){if(a.disabled)d(this).blur();
else{d(".ui-slider .ui-state-focus").removeClass("ui-state-focus");d(this).addClass("ui-state-focus")}}).blur(function(){d(this).removeClass("ui-state-focus")});this.handles.each(function(c){d(this).data("index.ui-slider-handle",c)});this.handles.keydown(function(c){var e=true,f=d(this).data("index.ui-slider-handle"),g,h,i;if(!b.options.disabled){switch(c.keyCode){case d.ui.keyCode.HOME:case d.ui.keyCode.END:case d.ui.keyCode.PAGE_UP:case d.ui.keyCode.PAGE_DOWN:case d.ui.keyCode.UP:case d.ui.keyCode.RIGHT:case d.ui.keyCode.DOWN:case d.ui.keyCode.LEFT:e=
false;if(!b._keySliding){b._keySliding=true;d(this).addClass("ui-state-active");g=b._start(c,f);if(g===false)return}break}i=b.options.step;g=b.options.values&&b.options.values.length?(h=b.values(f)):(h=b.value());switch(c.keyCode){case d.ui.keyCode.HOME:h=b._valueMin();break;case d.ui.keyCode.END:h=b._valueMax();break;case d.ui.keyCode.PAGE_UP:h=g+(b._valueMax()-b._valueMin())/5;break;case d.ui.keyCode.PAGE_DOWN:h=g-(b._valueMax()-b._valueMin())/5;break;case d.ui.keyCode.UP:case d.ui.keyCode.RIGHT:if(g===
b._valueMax())return;h=g+i;break;case d.ui.keyCode.DOWN:case d.ui.keyCode.LEFT:if(g===b._valueMin())return;h=g-i;break}b._slide(c,f,h);return e}}).keyup(function(c){var e=d(this).data("index.ui-slider-handle");if(b._keySliding){b._keySliding=false;b._stop(c,e);b._change(c,e);d(this).removeClass("ui-state-active")}});this._refreshValue();this._animateOff=false},destroy:function(){this.handles.remove();this.range.remove();this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-slider-disabled ui-widget ui-widget-content ui-corner-all").removeData("slider").unbind(".slider");
this._mouseDestroy();return this},_mouseCapture:function(b){var a=this.options,c,e,f,g,h,i;if(a.disabled)return false;this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()};this.elementOffset=this.element.offset();c={x:b.pageX,y:b.pageY};e=this._normValueFromMouse(c);f=this._valueMax()-this._valueMin()+1;h=this;this.handles.each(function(j){var k=Math.abs(e-h.values(j));if(f>k){f=k;g=d(this);i=j}});if(a.range===true&&this.values(1)===a.min){i+=1;g=d(this.handles[i])}if(this._start(b,
i)===false)return false;this._mouseSliding=true;h._handleIndex=i;g.addClass("ui-state-active").focus();a=g.offset();this._clickOffset=!d(b.target).parents().andSelf().is(".ui-slider-handle")?{left:0,top:0}:{left:b.pageX-a.left-g.width()/2,top:b.pageY-a.top-g.height()/2-(parseInt(g.css("borderTopWidth"),10)||0)-(parseInt(g.css("borderBottomWidth"),10)||0)+(parseInt(g.css("marginTop"),10)||0)};e=this._normValueFromMouse(c);this._slide(b,i,e);return this._animateOff=true},_mouseStart:function(){return true},
_mouseDrag:function(b){var a=this._normValueFromMouse({x:b.pageX,y:b.pageY});this._slide(b,this._handleIndex,a);return false},_mouseStop:function(b){this.handles.removeClass("ui-state-active");this._mouseSliding=false;this._stop(b,this._handleIndex);this._change(b,this._handleIndex);this._clickOffset=this._handleIndex=null;return this._animateOff=false},_detectOrientation:function(){this.orientation=this.options.orientation==="vertical"?"vertical":"horizontal"},_normValueFromMouse:function(b){var a;
if(this.orientation==="horizontal"){a=this.elementSize.width;b=b.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)}else{a=this.elementSize.height;b=b.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)}a=b/a;if(a>1)a=1;if(a<0)a=0;if(this.orientation==="vertical")a=1-a;b=this._valueMax()-this._valueMin();return this._trimAlignValue(this._valueMin()+a*b)},_start:function(b,a){var c={handle:this.handles[a],value:this.value()};if(this.options.values&&this.options.values.length){c.value=
this.values(a);c.values=this.values()}return this._trigger("start",b,c)},_slide:function(b,a,c){var e;if(this.options.values&&this.options.values.length){e=this.values(a?0:1);if(this.options.values.length===2&&this.options.range===true&&(a===0&&c>e||a===1&&c<e))c=e;if(c!==this.values(a)){e=this.values();e[a]=c;b=this._trigger("slide",b,{handle:this.handles[a],value:c,values:e});this.values(a?0:1);b!==false&&this.values(a,c,true)}}else if(c!==this.value()){b=this._trigger("slide",b,{handle:this.handles[a],
value:c});b!==false&&this.value(c)}},_stop:function(b,a){var c={handle:this.handles[a],value:this.value()};if(this.options.values&&this.options.values.length){c.value=this.values(a);c.values=this.values()}this._trigger("stop",b,c)},_change:function(b,a){if(!this._keySliding&&!this._mouseSliding){var c={handle:this.handles[a],value:this.value()};if(this.options.values&&this.options.values.length){c.value=this.values(a);c.values=this.values()}this._trigger("change",b,c)}},value:function(b){if(arguments.length){this.options.value=
this._trimAlignValue(b);this._refreshValue();this._change(null,0)}return this._value()},values:function(b,a){var c,e,f;if(arguments.length>1){this.options.values[b]=this._trimAlignValue(a);this._refreshValue();this._change(null,b)}if(arguments.length)if(d.isArray(arguments[0])){c=this.options.values;e=arguments[0];for(f=0;f<c.length;f+=1){c[f]=this._trimAlignValue(e[f]);this._change(null,f)}this._refreshValue()}else return this.options.values&&this.options.values.length?this._values(b):this.value();
else return this._values()},_setOption:function(b,a){var c,e=0;if(d.isArray(this.options.values))e=this.options.values.length;d.Widget.prototype._setOption.apply(this,arguments);switch(b){case "disabled":if(a){this.handles.filter(".ui-state-focus").blur();this.handles.removeClass("ui-state-hover");this.handles.attr("disabled","disabled");this.element.addClass("ui-disabled")}else{this.handles.removeAttr("disabled");this.element.removeClass("ui-disabled")}break;case "orientation":this._detectOrientation();
this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation);this._refreshValue();break;case "value":this._animateOff=true;this._refreshValue();this._change(null,0);this._animateOff=false;break;case "values":this._animateOff=true;this._refreshValue();for(c=0;c<e;c+=1)this._change(null,c);this._animateOff=false;break}},_value:function(){var b=this.options.value;return b=this._trimAlignValue(b)},_values:function(b){var a,c;if(arguments.length){a=this.options.values[b];
return a=this._trimAlignValue(a)}else{a=this.options.values.slice();for(c=0;c<a.length;c+=1)a[c]=this._trimAlignValue(a[c]);return a}},_trimAlignValue:function(b){if(b<this._valueMin())return this._valueMin();if(b>this._valueMax())return this._valueMax();var a=this.options.step,c=b%a;b=b-c;if(c>=a/2)b+=a;return parseFloat(b.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max},_refreshValue:function(){var b=this.options.range,a=this.options,c=this,
e=!this._animateOff?a.animate:false,f,g={},h,i,j,k;if(this.options.values&&this.options.values.length)this.handles.each(function(l){f=(c.values(l)-c._valueMin())/(c._valueMax()-c._valueMin())*100;g[c.orientation==="horizontal"?"left":"bottom"]=f+"%";d(this).stop(1,1)[e?"animate":"css"](g,a.animate);if(c.options.range===true)if(c.orientation==="horizontal"){if(l===0)c.range.stop(1,1)[e?"animate":"css"]({left:f+"%"},a.animate);if(l===1)c.range[e?"animate":"css"]({width:f-h+"%"},{queue:false,duration:a.animate})}else{if(l===
0)c.range.stop(1,1)[e?"animate":"css"]({bottom:f+"%"},a.animate);if(l===1)c.range[e?"animate":"css"]({height:f-h+"%"},{queue:false,duration:a.animate})}h=f});else{i=this.value();j=this._valueMin();k=this._valueMax();f=k!==j?(i-j)/(k-j)*100:0;g[c.orientation==="horizontal"?"left":"bottom"]=f+"%";this.handle.stop(1,1)[e?"animate":"css"](g,a.animate);if(b==="min"&&this.orientation==="horizontal")this.range.stop(1,1)[e?"animate":"css"]({width:f+"%"},a.animate);if(b==="max"&&this.orientation==="horizontal")this.range[e?
"animate":"css"]({width:100-f+"%"},{queue:false,duration:a.animate});if(b==="min"&&this.orientation==="vertical")this.range.stop(1,1)[e?"animate":"css"]({height:f+"%"},a.animate);if(b==="max"&&this.orientation==="vertical")this.range[e?"animate":"css"]({height:100-f+"%"},{queue:false,duration:a.animate})}}});d.extend(d.ui.slider,{version:"1.8.1"})})(jQuery);
(function(d){var s=0,u=0;d.widget("ui.tabs",{options:{add:null,ajaxOptions:null,cache:false,cookie:null,collapsible:false,disable:null,disabled:[],enable:null,event:"click",fx:null,idPrefix:"ui-tabs-",load:null,panelTemplate:"<div></div>",remove:null,select:null,show:null,spinner:"<em>Loading&#8230;</em>",tabTemplate:'<li><a href="#{href}"><span>#{label}</span></a></li>'},_create:function(){this._tabify(true)},_setOption:function(c,e){if(c=="selected")this.options.collapsible&&e==this.options.selected||
this.select(e);else{this.options[c]=e;this._tabify()}},_tabId:function(c){return c.title&&c.title.replace(/\s/g,"_").replace(/[^A-Za-z0-9\-_:\.]/g,"")||this.options.idPrefix+ ++s},_sanitizeSelector:function(c){return c.replace(/:/g,"\\:")},_cookie:function(){var c=this.cookie||(this.cookie=this.options.cookie.name||"ui-tabs-"+ ++u);return d.cookie.apply(null,[c].concat(d.makeArray(arguments)))},_ui:function(c,e){return{tab:c,panel:e,index:this.anchors.index(c)}},_cleanup:function(){this.lis.filter(".ui-state-processing").removeClass("ui-state-processing").find("span:data(label.tabs)").each(function(){var c=
d(this);c.html(c.data("label.tabs")).removeData("label.tabs")})},_tabify:function(c){function e(g,f){g.css({display:""});!d.support.opacity&&f.opacity&&g[0].style.removeAttribute("filter")}this.list=this.element.find("ol,ul").eq(0);this.lis=d("li:has(a[href])",this.list);this.anchors=this.lis.map(function(){return d("a",this)[0]});this.panels=d([]);var a=this,b=this.options,h=/^#.+/;this.anchors.each(function(g,f){var j=d(f).attr("href"),l=j.split("#")[0],p;if(l&&(l===location.toString().split("#")[0]||
(p=d("base")[0])&&l===p.href)){j=f.hash;f.href=j}if(h.test(j))a.panels=a.panels.add(a._sanitizeSelector(j));else if(j!="#"){d.data(f,"href.tabs",j);d.data(f,"load.tabs",j.replace(/#.*$/,""));j=a._tabId(f);f.href="#"+j;f=d("#"+j);if(!f.length){f=d(b.panelTemplate).attr("id",j).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").insertAfter(a.panels[g-1]||a.list);f.data("destroy.tabs",true)}a.panels=a.panels.add(f)}else b.disabled.push(g)});if(c){this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all");
this.list.addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.lis.addClass("ui-state-default ui-corner-top");this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom");if(b.selected===undefined){location.hash&&this.anchors.each(function(g,f){if(f.hash==location.hash){b.selected=g;return false}});if(typeof b.selected!="number"&&b.cookie)b.selected=parseInt(a._cookie(),10);if(typeof b.selected!="number"&&this.lis.filter(".ui-tabs-selected").length)b.selected=
this.lis.index(this.lis.filter(".ui-tabs-selected"));b.selected=b.selected||(this.lis.length?0:-1)}else if(b.selected===null)b.selected=-1;b.selected=b.selected>=0&&this.anchors[b.selected]||b.selected<0?b.selected:0;b.disabled=d.unique(b.disabled.concat(d.map(this.lis.filter(".ui-state-disabled"),function(g){return a.lis.index(g)}))).sort();d.inArray(b.selected,b.disabled)!=-1&&b.disabled.splice(d.inArray(b.selected,b.disabled),1);this.panels.addClass("ui-tabs-hide");this.lis.removeClass("ui-tabs-selected ui-state-active");
if(b.selected>=0&&this.anchors.length){this.panels.eq(b.selected).removeClass("ui-tabs-hide");this.lis.eq(b.selected).addClass("ui-tabs-selected ui-state-active");a.element.queue("tabs",function(){a._trigger("show",null,a._ui(a.anchors[b.selected],a.panels[b.selected]))});this.load(b.selected)}d(window).bind("unload",function(){a.lis.add(a.anchors).unbind(".tabs");a.lis=a.anchors=a.panels=null})}else b.selected=this.lis.index(this.lis.filter(".ui-tabs-selected"));this.element[b.collapsible?"addClass":
"removeClass"]("ui-tabs-collapsible");b.cookie&&this._cookie(b.selected,b.cookie);c=0;for(var i;i=this.lis[c];c++)d(i)[d.inArray(c,b.disabled)!=-1&&!d(i).hasClass("ui-tabs-selected")?"addClass":"removeClass"]("ui-state-disabled");b.cache===false&&this.anchors.removeData("cache.tabs");this.lis.add(this.anchors).unbind(".tabs");if(b.event!="mouseover"){var k=function(g,f){f.is(":not(.ui-state-disabled)")&&f.addClass("ui-state-"+g)},n=function(g,f){f.removeClass("ui-state-"+g)};this.lis.bind("mouseover.tabs",
function(){k("hover",d(this))});this.lis.bind("mouseout.tabs",function(){n("hover",d(this))});this.anchors.bind("focus.tabs",function(){k("focus",d(this).closest("li"))});this.anchors.bind("blur.tabs",function(){n("focus",d(this).closest("li"))})}var m,o;if(b.fx)if(d.isArray(b.fx)){m=b.fx[0];o=b.fx[1]}else m=o=b.fx;var q=o?function(g,f){d(g).closest("li").addClass("ui-tabs-selected ui-state-active");f.hide().removeClass("ui-tabs-hide").animate(o,o.duration||"normal",function(){e(f,o);a._trigger("show",
null,a._ui(g,f[0]))})}:function(g,f){d(g).closest("li").addClass("ui-tabs-selected ui-state-active");f.removeClass("ui-tabs-hide");a._trigger("show",null,a._ui(g,f[0]))},r=m?function(g,f){f.animate(m,m.duration||"normal",function(){a.lis.removeClass("ui-tabs-selected ui-state-active");f.addClass("ui-tabs-hide");e(f,m);a.element.dequeue("tabs")})}:function(g,f){a.lis.removeClass("ui-tabs-selected ui-state-active");f.addClass("ui-tabs-hide");a.element.dequeue("tabs")};this.anchors.bind(b.event+".tabs",
function(){var g=this,f=d(this).closest("li"),j=a.panels.filter(":not(.ui-tabs-hide)"),l=d(a._sanitizeSelector(this.hash));if(f.hasClass("ui-tabs-selected")&&!b.collapsible||f.hasClass("ui-state-disabled")||f.hasClass("ui-state-processing")||a._trigger("select",null,a._ui(this,l[0]))===false){this.blur();return false}b.selected=a.anchors.index(this);a.abort();if(b.collapsible)if(f.hasClass("ui-tabs-selected")){b.selected=-1;b.cookie&&a._cookie(b.selected,b.cookie);a.element.queue("tabs",function(){r(g,
j)}).dequeue("tabs");this.blur();return false}else if(!j.length){b.cookie&&a._cookie(b.selected,b.cookie);a.element.queue("tabs",function(){q(g,l)});a.load(a.anchors.index(this));this.blur();return false}b.cookie&&a._cookie(b.selected,b.cookie);if(l.length){j.length&&a.element.queue("tabs",function(){r(g,j)});a.element.queue("tabs",function(){q(g,l)});a.load(a.anchors.index(this))}else throw"jQuery UI Tabs: Mismatching fragment identifier.";d.browser.msie&&this.blur()});this.anchors.bind("click.tabs",
function(){return false})},destroy:function(){var c=this.options;this.abort();this.element.unbind(".tabs").removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible").removeData("tabs");this.list.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.anchors.each(function(){var e=d.data(this,"href.tabs");if(e)this.href=e;var a=d(this).unbind(".tabs");d.each(["href","load","cache"],function(b,h){a.removeData(h+".tabs")})});this.lis.unbind(".tabs").add(this.panels).each(function(){d.data(this,
"destroy.tabs")?d(this).remove():d(this).removeClass("ui-state-default ui-corner-top ui-tabs-selected ui-state-active ui-state-hover ui-state-focus ui-state-disabled ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide")});c.cookie&&this._cookie(null,c.cookie);return this},add:function(c,e,a){if(a===undefined)a=this.anchors.length;var b=this,h=this.options;e=d(h.tabTemplate.replace(/#\{href\}/g,c).replace(/#\{label\}/g,e));c=!c.indexOf("#")?c.replace("#",""):this._tabId(d("a",e)[0]);e.addClass("ui-state-default ui-corner-top").data("destroy.tabs",
true);var i=d("#"+c);i.length||(i=d(h.panelTemplate).attr("id",c).data("destroy.tabs",true));i.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide");if(a>=this.lis.length){e.appendTo(this.list);i.appendTo(this.list[0].parentNode)}else{e.insertBefore(this.lis[a]);i.insertBefore(this.panels[a])}h.disabled=d.map(h.disabled,function(k){return k>=a?++k:k});this._tabify();if(this.anchors.length==1){h.selected=0;e.addClass("ui-tabs-selected ui-state-active");i.removeClass("ui-tabs-hide");
this.element.queue("tabs",function(){b._trigger("show",null,b._ui(b.anchors[0],b.panels[0]))});this.load(0)}this._trigger("add",null,this._ui(this.anchors[a],this.panels[a]));return this},remove:function(c){var e=this.options,a=this.lis.eq(c).remove(),b=this.panels.eq(c).remove();if(a.hasClass("ui-tabs-selected")&&this.anchors.length>1)this.select(c+(c+1<this.anchors.length?1:-1));e.disabled=d.map(d.grep(e.disabled,function(h){return h!=c}),function(h){return h>=c?--h:h});this._tabify();this._trigger("remove",
null,this._ui(a.find("a")[0],b[0]));return this},enable:function(c){var e=this.options;if(d.inArray(c,e.disabled)!=-1){this.lis.eq(c).removeClass("ui-state-disabled");e.disabled=d.grep(e.disabled,function(a){return a!=c});this._trigger("enable",null,this._ui(this.anchors[c],this.panels[c]));return this}},disable:function(c){var e=this.options;if(c!=e.selected){this.lis.eq(c).addClass("ui-state-disabled");e.disabled.push(c);e.disabled.sort();this._trigger("disable",null,this._ui(this.anchors[c],this.panels[c]))}return this},
select:function(c){if(typeof c=="string")c=this.anchors.index(this.anchors.filter("[href$="+c+"]"));else if(c===null)c=-1;if(c==-1&&this.options.collapsible)c=this.options.selected;this.anchors.eq(c).trigger(this.options.event+".tabs");return this},load:function(c){var e=this,a=this.options,b=this.anchors.eq(c)[0],h=d.data(b,"load.tabs");this.abort();if(!h||this.element.queue("tabs").length!==0&&d.data(b,"cache.tabs"))this.element.dequeue("tabs");else{this.lis.eq(c).addClass("ui-state-processing");
if(a.spinner){var i=d("span",b);i.data("label.tabs",i.html()).html(a.spinner)}this.xhr=d.ajax(d.extend({},a.ajaxOptions,{url:h,success:function(k,n){d(e._sanitizeSelector(b.hash)).html(k);e._cleanup();a.cache&&d.data(b,"cache.tabs",true);e._trigger("load",null,e._ui(e.anchors[c],e.panels[c]));try{a.ajaxOptions.success(k,n)}catch(m){}},error:function(k,n){e._cleanup();e._trigger("load",null,e._ui(e.anchors[c],e.panels[c]));try{a.ajaxOptions.error(k,n,c,b)}catch(m){}}}));e.element.dequeue("tabs");return this}},
abort:function(){this.element.queue([]);this.panels.stop(false,true);this.element.queue("tabs",this.element.queue("tabs").splice(-2,2));if(this.xhr){this.xhr.abort();delete this.xhr}this._cleanup();return this},url:function(c,e){this.anchors.eq(c).removeData("cache.tabs").data("load.tabs",e);return this},length:function(){return this.anchors.length}});d.extend(d.ui.tabs,{version:"1.8.1"});d.extend(d.ui.tabs.prototype,{rotation:null,rotate:function(c,e){var a=this,b=this.options,h=a._rotate||(a._rotate=
function(i){clearTimeout(a.rotation);a.rotation=setTimeout(function(){var k=b.selected;a.select(++k<a.anchors.length?k:0)},c);i&&i.stopPropagation()});e=a._unrotate||(a._unrotate=!e?function(i){i.clientX&&a.rotate(null)}:function(){t=b.selected;h()});if(c){this.element.bind("tabsshow",h);this.anchors.bind(b.event+".tabs",e);h()}else{clearTimeout(a.rotation);this.element.unbind("tabsshow",h);this.anchors.unbind(b.event+".tabs",e);delete this._rotate;delete this._unrotate}return this}})})(jQuery);

/*
 * jQuery JSON Plugin
 * version: 2.1 (2009-08-14)
 *
 * This document is licensed as free software under the terms of the
 * MIT License: http://www.opensource.org/licenses/mit-license.php
 *
 * Brantley Harris wrote this plugin. It is based somewhat on the JSON.org 
 * website's http://www.json.org/json2.js, which proclaims:
 * "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.", a sentiment that
 * I uphold.
 *
 * It is also influenced heavily by MochiKit's serializeJSON, which is 
 * copyrighted 2005 by Bob Ippolito.
 */
 
(function($) {
    /** jQuery.toJSON( json-serializble )
        Converts the given argument into a JSON respresentation.

        If an object has a "toJSON" function, that will be used to get the representation.
        Non-integer/string keys are skipped in the object, as are keys that point to a function.

        json-serializble:
            The *thing* to be converted.
     **/
    $.toJSON = function(o)
    {
        if (typeof(JSON) == 'object' && JSON.stringify)
            return JSON.stringify(o);
        
        var type = typeof(o);
    
        if (o === null)
            return "null";
    
        if (type == "undefined")
            return undefined;
        
        if (type == "number" || type == "boolean")
            return o + "";
    
        if (type == "string")
            return $.quoteString(o);
    
        if (type == 'object')
        {
            if (typeof o.toJSON == "function") 
                return $.toJSON( o.toJSON() );
            
            if (o.constructor === Date)
            {
                var month = o.getUTCMonth() + 1;
                if (month < 10) month = '0' + month;

                var day = o.getUTCDate();
                if (day < 10) day = '0' + day;

                var year = o.getUTCFullYear();
                
                var hours = o.getUTCHours();
                if (hours < 10) hours = '0' + hours;
                
                var minutes = o.getUTCMinutes();
                if (minutes < 10) minutes = '0' + minutes;
                
                var seconds = o.getUTCSeconds();
                if (seconds < 10) seconds = '0' + seconds;
                
                var milli = o.getUTCMilliseconds();
                if (milli < 100) milli = '0' + milli;
                if (milli < 10) milli = '0' + milli;

                return '"' + year + '-' + month + '-' + day + 'T' +
                             hours + ':' + minutes + ':' + seconds + 
                             '.' + milli + 'Z"'; 
            }

            if (o.constructor === Array) 
            {
                var ret = [];
                for (var i = 0; i < o.length; i++)
                    ret.push( $.toJSON(o[i]) || "null" );

                return "[" + ret.join(",") + "]";
            }
        
            var pairs = [];
            for (var k in o) {
                var name;
                var type = typeof k;

                if (type == "number")
                    name = '"' + k + '"';
                else if (type == "string")
                    name = $.quoteString(k);
                else
                    continue;  //skip non-string or number keys
            
                if (typeof o[k] == "function") 
                    continue;  //skip pairs where the value is a function.
            
                var val = $.toJSON(o[k]);
            
                pairs.push(name + ":" + val);
            }

            return "{" + pairs.join(", ") + "}";
        }
    };

    /** jQuery.evalJSON(src)
        Evaluates a given piece of json source.
     **/
    $.evalJSON = function(src)
    {
        if (typeof(JSON) == 'object' && JSON.parse)
            return JSON.parse(src);
        return eval("(" + src + ")");
    };
    
    /** jQuery.secureEvalJSON(src)
        Evals JSON in a way that is *more* secure.
    **/
    $.secureEvalJSON = function(src)
    {
        if (typeof(JSON) == 'object' && JSON.parse)
            return JSON.parse(src);
        
        var filtered = src;
        filtered = filtered.replace(/\\["\\\/bfnrtu]/g, '@');
        filtered = filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
        filtered = filtered.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
        
        if (/^[\],:{}\s]*$/.test(filtered))
            return eval("(" + src + ")");
        else
            throw new SyntaxError("Error parsing JSON, source is not valid.");
    };

    /** jQuery.quoteString(string)
        Returns a string-repr of a string, escaping quotes intelligently.  
        Mostly a support function for toJSON.
    
        Examples:
            >>> jQuery.quoteString("apple")
            "apple"
        
            >>> jQuery.quoteString('"Where are we going?", she asked.')
            "\"Where are we going?\", she asked."
     **/
    $.quoteString = function(string)
    {
        if (string.match(_escapeable))
        {
            return '"' + string.replace(_escapeable, function (a) 
            {
                var c = _meta[a];
                if (typeof c === 'string') return c;
                c = a.charCodeAt();
                return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
            }) + '"';
        }
        return '"' + string + '"';
    };
    
    var _escapeable = /["\\\x00-\x1f\x7f-\x9f]/g;
    
    var _meta = {
        '\b': '\\b',
        '\t': '\\t',
        '\n': '\\n',
        '\f': '\\f',
        '\r': '\\r',
        '"' : '\\"',
        '\\': '\\\\'
    };
})(jQuery);

/*jslint browser: true */ /*global jQuery: true */

/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

// TODO JsDoc

/**
 * Create a cookie with the given key and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String key The key of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given key.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String key The key of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function (key, value, options) {
    
    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }
        
        value = String(value);
        
        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

/* Simple JavaScript Inheritance
 * By John Resig http://ejohn.org/
 * MIT Licensed.
 */
// Inspired by base2 and Prototype
(function(){
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;

  // The base Class implementation (does nothing)
  this.Class = function(){};
 
  // Create a new Class that inherits from this class
  Class.extend = function(prop) {
    var _super = this.prototype;
   
    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;
   
    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" &&
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;
           
            // Add a new ._super() method that is the same method
            // but on the super-class
            this._super = _super[name];
           
            // The method only need to be bound temporarily, so we
            // remove it when we're done executing
            var ret = fn.apply(this, arguments);       
            this._super = tmp;
           
            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }
    
    Class.implement = function(implementor){
		var impl = new implementor();
		impl.implement(Class);
    	return Class;
    }
   
    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }
   
    // Populate our constructed prototype object
    Class.prototype = prototype;
   
    // Enforce the constructor to be what we expect
    Class.constructor = Class;

    // And make this class extendable
    Class.extend = arguments.callee;
   
    return Class;
  };
})();
//micro template based on John Resg code
function tmpl(tmpl_id,data){
//	try {
		if ( typeof tmpl.cache == 'undefined' ) {
			tmpl.cache = new Array();
	    }
		if( tmpl.cache[tmpl_id]!=null ){
			var fn = tmpl.cache[tmpl_id];
			return fn(data);		
		}
		str = document.getElementById(tmpl_id).innerHTML;
		str = str.replace(/\\/g, "@SPC@");
		str = str.replace(/'/g, "&apos;");
		fnStr = "var p=[],print=function(){p.push.apply(p,arguments);};" +
	    
	    // Introduce the data as local variables using with(){}
	    "with(obj){p.push('" +
	    
	    // Convert the template into pure JavaScript
	    str
	      .replace(/[\r\t\n]/g, " ")
	      .split("<%").join("\t")
	      .replace(/((^|%>)[^\t]*)'/g, "$1\r")
	      .replace(/\t=(.*?)%>/g, "',$1,'")
	      .split("\t").join("');")
	      .split("%>").join("p.push('")
	      .split("\r").join("\\'")
	  + "');}return p.join('');";
		fnStr = fnStr.replace(/@SPC@/g, "\\");
		var fn = new Function("obj", fnStr);
		tmpl.cache[tmpl_id] = fn;
		return fn(data);
//	} catch (e) {
//		return "";
//	}
}

(function ($) {
    $.format = (function () {

		function strMonth(value) {
			switch (parseInt(value)) {
                case 1:
                    return "Jan";
                case 2:
                    return "Feb";
                case 3:
                    return "Mar";
                case 4:
                    return "Apr";
                case 5:
                    return "May";
                case 6:
                    return "Jun";
                case 7:
                    return "Jul";
                case 8:
                    return "Aug";
                case 9:
                    return "Sep";
                case 10:
                    return "Oct";
                case 11:
                    return "Nov";
                case 12:
                    return "Dec";
                default:
                    return value;
			}
		}
	
        var parseMonth = function (value) {
            switch (value) {
                case "Jan":
                    return "01";
                case "Feb":
                    return "02";
                case "Mar":
                    return "03";
                case "Apr":
                    return "04";
                case "May":
                    return "05";
                case "Jun":
                    return "06";
                case "Jul":
                    return "07";
                case "Aug":
                    return "08";
                case "Sep":
                    return "09";
                case "Oct":
                    return "10";
                case "Nov":
                    return "11";
                case "Dec":
                    return "12";
                default:
                    return value;
            }
        };

        var parseTime = function (value) {
            var retValue = value;
            if (retValue.indexOf(".") !== -1) {
                retValue = retValue.substring(0, retValue.indexOf("."));
            }

            var values3 = retValue.split(":");

            if (values3.length === 3) {
                hour = values3[0];
                minute = values3[1];
                second = values3[2];

                return {
                    time: retValue,
                    hour: hour,
                    minute: minute,
                    second: second
                };
            } else {
                return {
                    time: "",
                    hour: "",
                    minute: "",
                    second: ""
                };
            }
        };

        return {
            date: function (value, format) {
                //value = new java.util.Date()
                //2009-12-18 10:54:50.546
                try {
                    var year = null;
                    var month = null;
                    var dayOfMonth = null;
                    var time = null; //json, time, hour, minute, second
                    if (typeof value.getFullYear === "function") {
                        year = value.getFullYear();
                        month = value.getMonth() + 1;
                        dayOfMonth = value.getDate();
                        time = parseTime(value.toTimeString());
                    } else if (value.search(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.?\d{0,3}\+\d{2}:\d{2}/) != -1) { // 2009-04-19T16:11:05+02:00
                        var values = value.split(/[T\+-]/);
                        year = values[0];
                        month = values[1];
                        dayOfMonth = values[2];
                        time = parseTime(values[3].split(".")[0]);
                    } else {
                        var values = value.split(" ");
                        switch (values.length) {
                            case 6: //Wed Jan 13 10:43:41 CET 2010
                                year = values[5];
                                month = parseMonth(values[1]);
                                dayOfMonth = values[2];
                                time = parseTime(values[3]);
                                break;
                            case 2: //2009-12-18 10:54:50.546
                                var values2 = values[0].split("-");
                                year = values2[0];
                                month = values2[1];
                                dayOfMonth = values2[2];
                                time = parseTime(values[1]);
                                break;
						    case 7: // Tue Mar 01 2011 12:01:42 GMT-0800 (PST)
	                            year = values[3];
	                            month = parseMonth(values[1]);
	                            dayOfMonth = values[2];
	                            time = parseTime(values[4]);
	                            break;
                            default:
                                return value;
                        }
                    }

                    var pattern = "";
                    var retValue = "";
                    //Issue 1 - variable scope issue in format.date 
                    //Thanks jakemonO
                    for (var i = 0; i < format.length; i++) {
                        var currentPattern = format.charAt(i);
                        pattern += currentPattern;
                        switch (pattern) {
                            case "dd":
                                retValue += dayOfMonth;
                                pattern = "";
                                break;
                            case "MMM":
                                retValue += strMonth(month);
                                pattern = "";
                                break;
                            case "MM":
                                if (format.charAt(i+1) == "M") {
                                    break;
                                }
                                retValue += month;
                                pattern = "";
                                break;
                            case "yyyy":
                                retValue += year;
                                pattern = "";
                                break;
                            case "HH":
                                retValue += time.hour;
                                pattern = "";
                                break;
                            case "hh":
                                //time.hour is "00" as string == is used instead of ===
                                retValue += (time.hour == 0 ? 12 : time.hour < 13 ? time.hour : time.hour - 12);
                                pattern = "";
                                break;
                            case "mm":
                                retValue += time.minute;
                                pattern = "";
                                break;
                            case "ss":
                                //ensure only seconds are added to the return string
                                retValue += time.second.substring(0, 2);
                                pattern = "";
                                break;
                            //case "tz":
                            //    //parse out the timezone information
                            //    retValue += time.second.substring(3, time.second.length);
                            //    pattern = "";
                            //    break;
                            case "a":
                                retValue += time.hour >= 12 ? "PM" : "AM";
                                pattern = "";
                                break;
                            case " ":
                                retValue += currentPattern;
                                pattern = "";
                                break;
                            case "/":
                                retValue += currentPattern;
                                pattern = "";
                                break;
                            case ":":
                                retValue += currentPattern;
                                pattern = "";
                                break;
                            default:
                                if (pattern.length === 2 && pattern.indexOf("y") !== 0) {
                                    retValue += pattern.substring(0, 1);
                                    pattern = pattern.substring(1, 2);
                                } else if ((pattern.length === 3 && pattern.indexOf("yyy") === -1)) {
                                    pattern = "";
                                }
                        }
                    }
                    return retValue;
                } catch (e) {
//                    console.log(e);
                    return value;
                }
            }
        };
    } ());
} (jQuery));


$(document).ready(function () {
    $(".shortDateFormat").each(function (idx, elem) {
        if ($(elem).is(":input")) {
            $(elem).val($.format.date($(elem).val(), 'dd/MM/yyyy'));
        } else {
            $(elem).text($.format.date($(elem).text(), 'dd/MM/yyyy'));
        }
    });
    $(".longDateFormat").each(function (idx, elem) {
        if ($(elem).is(":input")) {
            $(elem).val($.format.date($(elem).val(), 'dd/MM/yyyy hh:mm:ss'));
        } else {
            $(elem).text($.format.date($(elem).text(), 'dd/MM/yyyy hh:mm:ss'));
        }
    });
});

/*
 AnythingSlider v1.5.7.3 minified using Google Closure Compiler
 By Chris Coyier: http://css-tricks.com
 with major improvements by Doug Neiner: http://pixelgraphics.us/
 based on work by Remy Sharp: http://jqueryfordesigners.com/
*/

(function(c){c.anythingSlider=function(g,i){var a=this;a.$el=c(g).addClass("anythingBase").wrap('<div class="anythingSlider"><div class="anythingWindow" /></div>');a.$el.data("AnythingSlider",a);a.init=function(){a.options=c.extend({},c.anythingSlider.defaults,i);c.isFunction(a.options.onBeforeInitialize)&&a.$el.bind("before_initialize",a.options.onBeforeInitialize);a.$el.trigger("before_initialize",a);a.$wrapper=a.$el.parent().closest("div.anythingSlider").addClass("anythingSlider-"+a.options.theme); a.$window=a.$el.closest("div.anythingWindow");a.$controls=c('<div class="anythingControls"></div>').appendTo(a.options.appendControlsTo!==null&&c(a.options.appendControlsTo).length?c(a.options.appendControlsTo):a.$wrapper);a.win=window;a.$win=c(a.win);a.$nav=c('<ul class="thumbNav" />').appendTo(a.$controls);a.timer=null;a.flag=false;a.playing=false;a.hovered=false;a.panelSize=[];a.currentPage=a.options.startPanel;a.adjustLimit=a.options.infiniteSlides?0:1;a.options.playRtl&&a.$wrapper.addClass("rtl"); a.original=[a.options.autoPlay,a.options.buildNavigation,a.options.buildArrows];a.updateSlider();a.$currentPage=a.$items.eq(a.currentPage);a.$lastPage=a.$currentPage;a.runTimes=c("div.anythingSlider").index(a.$wrapper)+1;a.regex=RegExp("panel"+a.runTimes+"-(\\d+)","i");if(!c.isFunction(c.easing[a.options.easing]))a.options.easing="swing";a.options.theme!=="default"&&!c("link[href*="+a.options.theme+"]").length&&c("body").append('<link rel="stylesheet" href="'+a.options.themeDirectory.replace(/\{themeName\}/g, a.options.theme)+'" type="text/css" />');a.options.pauseOnHover&&a.$wrapper.hover(function(){if(a.playing){a.$el.trigger("slideshow_paused",a);a.clearTimer(true)}},function(){if(a.playing){a.$el.trigger("slideshow_unpaused",a);a.startStop(a.playing,true)}});var b=a.options.hashTags?a.gotoHash()||a.options.startPanel:a.options.startPanel;a.setCurrentPage(b,false);a.slideControls(false);a.$wrapper.bind("mouseenter mouseleave",function(e){a.hovered=e.type==="mouseenter"?true:false;a.slideControls(a.hovered, false)});a.options.enableKeyboard&&c(document).keyup(function(e){if(a.$wrapper.is(".activeSlider"))switch(e.which){case 39:a.goForward();break;case 37:a.goBack()}});var d="slideshow_paused slideshow_unpaused slide_init slide_begin slideshow_stop slideshow_start initialized swf_completed".split(" ");c.each("onShowPause onShowUnpause onSlideInit onSlideBegin onShowStop onShowStart onInitialized onSWFComplete".split(" "),function(e,f){c.isFunction(a.options[f])&&a.$el.bind(d[e],a.options[f])});c.isFunction(a.options.onSlideComplete)&& a.$el.bind("slide_complete",function(){setTimeout(function(){a.options.onSlideComplete(a)},0)});a.$el.trigger("initialized",a)};a.updateSlider=function(){a.$el.find("li.cloned").remove();a.$nav.empty();a.$items=a.$el.find("> li");a.pages=a.$items.length;if(a.options.resizeContents){a.options.width&&a.$wrapper.add(a.$items).css("width",a.options.width);a.options.height&&a.$wrapper.add(a.$items).css("height",a.options.height)}if(a.pages===1){a.options.autoPlay=false;a.options.buildNavigation=false; a.options.buildArrows=false;a.$controls.hide();a.$nav.hide();a.$forward&&a.$forward.add(a.$back).hide()}else{a.options.autoPlay=a.original[0];a.options.buildNavigation=a.original[1];a.options.buildArrows=a.original[2];a.$controls.show();a.$nav.show();a.$forward&&a.$forward.add(a.$back).show()}a.buildNavigation();if(a.options.autoPlay){a.playing=!a.options.startStopped;a.buildAutoPlay()}a.options.buildArrows&&a.buildNextBackButtons();a.$el.prepend(a.options.infiniteSlides?a.$items.filter(":last").clone().addClass("cloned").removeAttr("id"): c('<li class="cloned" />'));a.$el.append(a.options.infiniteSlides?a.$items.filter(":first").clone().addClass("cloned").removeAttr("id"):c('<li class="cloned" />'));a.$el.find("li.cloned").each(function(){c(this).html(c(this).html().replace(/<a/gi,"<span").replace(/\/a>/gi,"/span>"));c(this).find("[id]").removeAttr("id")});a.$items=a.$el.find("> li").addClass("panel");a.setDimensions();a.options.resizeContents||a.$win.load(function(){a.setDimensions()});if(a.currentPage>a.pages){a.currentPage=a.pages; a.setCurrentPage(a.pages,false)}a.$nav.find("a").eq(a.currentPage-1).addClass("cur");a.hasEmb=a.$items.find("embed[src*=youtube]").length;a.hasSwfo=typeof swfobject!=="undefined"&&swfobject.hasOwnProperty("embedSWF")&&c.isFunction(swfobject.embedSWF)?true:false;a.hasEmb&&a.hasSwfo&&a.$items.find("embed[src*=youtube]").each(function(b){var d=c(this).parent()[0].tagName==="OBJECT"?c(this).parent():c(this);d.wrap('<div id="ytvideo'+b+'"></div>');swfobject.embedSWF(c(this).attr("src")+"&enablejsapi=1&version=3&playerapiid=ytvideo"+ b,"ytvideo"+b,d.attr("width"),d.attr("height"),"10",null,null,{allowScriptAccess:"always",wmode:a.options.addWmodeToObject,allowfullscreen:true},{"class":d.attr("class"),style:d.attr("style")},function(){b>=a.hasEmb-1&&a.$el.trigger("swf_completed",a)})});a.$items.find("a").unbind("focus").bind("focus",function(b){a.$items.find(".focusedLink").removeClass("focusedLink");c(this).addClass("focusedLink");var d=c(this).closest(".panel");if(!d.is(".activePage")){a.gotoPage(a.$items.index(d));b.preventDefault()}})}; a.buildNavigation=function(){a.options.buildNavigation&&a.pages>1&&a.$items.filter(":not(.cloned)").each(function(b){var d=b+1;b=(d===1?"first":"")+(d===a.pages?"last":"");b=c('<a href="#"></a>').addClass("panel"+d).wrap('<li class="'+b+'" />');a.$nav.append(b.parent());if(c.isFunction(a.options.navigationFormatter)){var e=a.options.navigationFormatter(d,c(this));b.html(e);parseInt(b.css("text-indent"),10)<0&&b.addClass(a.options.tooltipClass).attr("title",e)}else b.text(d);b.bind(a.options.clickControls, function(f){if(!a.flag&&a.options.enableNavigation){a.flag=true;setTimeout(function(){a.flag=false},100);a.gotoPage(d);a.options.hashTags&&a.setHash(d)}f.preventDefault()})})};a.buildNextBackButtons=function(){if(!a.$forward){a.$forward=c('<span class="arrow forward"><a href="#">'+a.options.forwardText+"</a></span>");a.$back=c('<span class="arrow back"><a href="#">'+a.options.backText+"</a></span>");a.$back.bind(a.options.clickArrows,function(b){a.goBack();b.preventDefault()});a.$forward.bind(a.options.clickArrows, function(b){a.goForward();b.preventDefault()});a.$back.add(a.$forward).find("a").bind("focusin focusout",function(){c(this).toggleClass("hover")});a.$wrapper.prepend(a.$forward).prepend(a.$back);a.$arrowWidth=a.$forward.width()}};a.buildAutoPlay=function(){if(!a.$startStop){a.$startStop=c("<a href='#' class='start-stop'></a>").html(a.playing?a.options.stopText:a.options.startText);a.$controls.prepend(a.$startStop);a.$startStop.bind(a.options.clickSlideshow,function(b){if(a.options.enablePlay){a.startStop(!a.playing); if(a.playing)a.options.playRtl?a.goBack(true):a.goForward(true)}b.preventDefault()}).bind("focusin focusout",function(){c(this).toggleClass("hover")});a.startStop(a.playing)}};a.setDimensions=function(){var b,d,e,f,j,h=0,k=a.$window.width(),l=a.$win.width();a.$items.each(function(m){e=c(this).children("*");if(a.options.resizeContents){b=parseInt(a.options.width,10)||k;d=parseInt(a.options.height,10)||a.$window.height();c(this).css({width:b,height:d});if(e.length===1){e.css({width:"100%",height:"100%"}); e[0].tagName==="OBJECT"&&e.find("embed").andSelf().attr({width:"100%",height:"100%"})}}else{b=c(this).width();j=b>=l?true:false;if(e.length===1&&j){f=e.width()>=l?k:e.width();c(this).css("width",f);e.css("max-width",f);b=f}b=j?a.options.width||k:b;c(this).css("width",b);d=c(this).outerHeight();c(this).css("height",d)}a.panelSize[m]=[b,d,h];h+=b});a.$el.css("width",h<a.options.maxOverallWidth?h:a.options.maxOverallWidth)};a.gotoPage=function(b,d,e){if(a.pages!==1){a.$lastPage=a.$items.eq(a.currentPage); if(typeof b!=="number"){b=a.options.startPage;a.setCurrentPage(a.options.startPage)}if(!(a.hasEmb&&a.checkVideo(a.playing))){if(b>a.pages+1-a.adjustLimit)b=!a.options.infiniteSlides&&!a.options.stopAtEnd?1:a.pages;if(b<a.adjustLimit)b=!a.options.infiniteSlides&&!a.options.stopAtEnd?a.pages:1;a.$currentPage=a.$items.eq(b);a.currentPage=b;a.$el.trigger("slide_init",a);a.slideControls(true,false);if(d!==true)d=false;if(!d||a.options.stopAtEnd&&b===a.pages)a.startStop(false);a.$el.trigger("slide_begin", a);a.options.resizeContents||a.$wrapper.filter(":not(:animated)").animate({width:a.panelSize[b][0],height:a.panelSize[b][1]},{queue:false,duration:a.options.animationTime,easing:a.options.easing});a.$window.filter(":not(:animated)").animate({scrollLeft:a.panelSize[b][2]},{queue:false,duration:a.options.animationTime,easing:a.options.easing,complete:function(){a.endAnimation(b,e)}})}}};a.endAnimation=function(b,d){if(b===0){a.$window.scrollLeft(a.panelSize[a.pages][2]);b=a.pages}else if(b>a.pages){a.$window.scrollLeft(a.panelSize[1][2]); b=1}a.setCurrentPage(b,false);a.$items.removeClass("activePage").eq(b).addClass("activePage");a.hovered||a.slideControls(false);if(a.hasEmb){var e=a.$currentPage.find("object[id*=ytvideo], embed[id*=ytvideo]");e.length&&c.isFunction(e[0].getPlayerState)&&e[0].getPlayerState()>0&&e[0].getPlayerState()!==5&&e[0].playVideo()}a.$el.trigger("slide_complete",a);typeof d==="function"&&d(a);a.options.autoPlayLocked&&!a.playing&&setTimeout(function(){a.startStop(true)},a.options.resumeDelay-a.options.delay)}; a.setCurrentPage=function(b,d){if(b>a.pages+1-a.adjustLimit)b=a.pages-a.adjustLimit;if(b<a.adjustLimit)b=1;if(a.options.buildNavigation){a.$nav.find(".cur").removeClass("cur");a.$nav.find("a").eq(b-1).addClass("cur")}if(!a.options.infiniteSlides&&a.options.stopAtEnd){a.$wrapper.find("span.forward")[b===a.pages?"addClass":"removeClass"]("disabled");a.$wrapper.find("span.back")[b===1?"addClass":"removeClass"]("disabled");b===a.pages&&a.playing&&a.startStop()}if(!d){a.$wrapper.css({width:a.panelSize[b][0], height:a.panelSize[b][1]});a.$wrapper.scrollLeft(0);a.$window.scrollLeft(a.panelSize[b][2])}a.currentPage=b;if(!a.$wrapper.is(".activeSlider")){c(".activeSlider").removeClass("activeSlider");a.$wrapper.addClass("activeSlider")}};a.goForward=function(b){if(b!==true){b=false;a.startStop(false)}a.gotoPage(a.currentPage+1,b)};a.goBack=function(b){if(b!==true){b=false;a.startStop(false)}a.gotoPage(a.currentPage-1,b)};a.gotoHash=function(){var b=a.win.location.hash.match(a.regex);return b===null?"":parseInt(b[1], 10)};a.setHash=function(b){var d="panel"+a.runTimes+"-",e=a.win.location.hash;if(typeof e!=="undefined")a.win.location.hash=e.indexOf(d)>0?e.replace(a.regex,d+b):e+"&"+d+b};a.slideControls=function(b){var d=b?"slideDown":"slideUp",e=b?0:a.options.animationTime,f=b?a.options.animationTime:0;b=b?0:1;a.options.toggleControls&&a.$controls.stop(true,true).delay(e)[d](a.options.animationTime/2).delay(f);if(a.options.buildArrows&&a.options.toggleArrows){if(!a.hovered&&a.playing){b=1;f=0}a.$forward.stop(true, true).delay(e).animate({right:b*a.$arrowWidth,opacity:f},a.options.animationTime/2);a.$back.stop(true,true).delay(e).animate({left:b*a.$arrowWidth,opacity:f},a.options.animationTime/2)}};a.clearTimer=function(b){if(a.timer){a.win.clearInterval(a.timer);b||a.$el.trigger("slideshow_stop",a)}};a.startStop=function(b,d){if(b!==true)b=false;b&&!d&&a.$el.trigger("slideshow_start",a);a.playing=b;if(a.options.autoPlay){a.$startStop.toggleClass("playing",b).html(b?a.options.stopText:a.options.startText);if(parseInt(a.$startStop.css("text-indent"), 10)<0)a.$startStop.addClass(a.options.tooltipClass).attr("title",b?"Stop":"Start")}if(b){a.clearTimer(true);a.timer=a.win.setInterval(function(){a.hasEmb&&a.checkVideo(b)||(a.options.playRtl?a.goBack(true):a.goForward(true))},a.options.delay)}else a.clearTimer()};a.checkVideo=function(b){var d,e,f=false;a.$items.find("object[id*=ytvideo], embed[id*=ytvideo]").each(function(){d=c(this);if(d.length&&c.isFunction(d[0].getPlayerState)){e=d[0].getPlayerState();if(b&&(e===1||e>2)&&a.$items.index(d.closest("li.panel"))=== a.currentPage&&a.options.resumeOnVideoEnd)f=true;else e>0&&d[0].pauseVideo()}});return f};a.init()};c.anythingSlider.defaults={width:null,height:null,resizeContents:true,tooltipClass:"tooltip",theme:"default",themeDirectory:"css/theme-{themeName}.css",startPanel:1,hashTags:true,infiniteSlides:true,enableKeyboard:true,buildArrows:true,toggleArrows:false,buildNavigation:true,enableNavigation:true,toggleControls:false,appendControlsTo:null,navigationFormatter:null,forwardText:"&raquo;",backText:"&laquo;", enablePlay:true,autoPlay:true,autoPlayLocked:false,startStopped:false,pauseOnHover:true,resumeOnVideoEnd:true,stopAtEnd:false,playRtl:false,startText:"Start",stopText:"Stop",delay:3E3,resumeDelay:15E3,animationTime:600,easing:"swing",clickArrows:"click",clickControls:"click focusin",clickSlideshow:"click",addWmodeToObject:"opaque",maxOverallWidth:32766};c.fn.anythingSlider=function(g,i){return this.each(function(){var a=c(this).data("AnythingSlider");if((typeof g).match("object|undefined"))if(a)a.updateSlider(); else new c.anythingSlider(this,g);else if(/\d/.test(g)&&!isNaN(g)&&a){var b=typeof g==="number"?g:parseInt(c.trim(g),10);b>=1&&b<=a.pages&&a.gotoPage(b,false,i)}})}})(jQuery);

/*
 * jQuery EasIng v1.1.2 - http://gsgd.co.uk/sandbox/jquery.easIng.php
 *
 * Uses the built In easIng capabilities added In jQuery 1.1
 * to offer multiple easIng options
 *
 * Copyright (c) 2007 George Smith
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */

// t: current time, b: begInnIng value, c: change In value, d: duration

jQuery.extend( jQuery.easing,
{
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158; 
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});
(function(d) {
	var e = 0;
	d
			.widget(
					"ui.autocomplete",
					{
						options : {
							appendTo : "body",
							delay : 300,
							minLength : 1,
							position : {
								my : "left top",
								at : "left bottom",
								collision : "none"
							},
							source : null
						},
						pending : 0,
						_create : function() {
							var a = this, b = this.element[0].ownerDocument, g;
							this.element
									.addClass("ui-autocomplete-input")
									.attr("autocomplete", "off")
									.attr({
										role : "textbox",
										"aria-autocomplete" : "list",
										"aria-haspopup" : "true"
									})
									.bind(
											"keydown.autocomplete",
											function(c) {
												if (!(a.options.disabled || a.element
														.attr("readonly"))) {
													g = false;
													var f = d.ui.keyCode;
													switch (c.keyCode) {
													case f.PAGE_UP:
														a._move("previousPage",
																c);
														break;
													case f.PAGE_DOWN:
														a._move("nextPage", c);
														break;
													case f.UP:
														a._move("previous", c);
														c.preventDefault();
														break;
													case f.DOWN:
														a._move("next", c);
														c.preventDefault();
														break;
													case f.ENTER:
													case f.NUMPAD_ENTER:
														var id = a.element.attr("id");
														// chỉ lấy thông tin của ô input search
														if(id == "to" || id == "toPerson"){
															if (a.menu.active) {
																g = true;
																c.preventDefault();
															} else{
																if ($('#tabs li.ui-tabs-selected span.ui-tab-font').hasClass('tab-person')){
																	onClickPerson();
																} else{
																	if ($('#tabs li.ui-tabs-selected span.ui-tab-font').hasClass('tab-knowledge')){
																		onClickQuestion();
																	}
																}
															}
														}
													case f.TAB:
														if (!a.menu.active)
															return;
														a.menu.select(c);
														break;
													case f.ESCAPE:
														a.element.val(a.term);
														a.close(c);
														break;
													case f.BACKSPACE:
														var tmp_a = a.menu.element;
														//console.log("BACK SPACE");
														if (a.element.val() == 0){
															$('input[class="ui-autocomplete-input"]').prev("span").remove();
															$('li[role="menuitem"]').each(function(){$(this).remove();});
														}
														var w = 0;
														$("#friends span").each(function(){
															w += $(this).outerWidth(true);
														});
														var adaptive_width = $("#friends").width() - w;
														var min = 120;
														if (adaptive_width < min){
															adaptive_width = $("#friends").width();
														}
														$("#to").width(adaptive_width);
													default:
														clearTimeout(a.searching);
														a.searching = setTimeout(
																function() {
																	if (a.term != a.element
																			.val()) {
																		a.selectedItem = null;
																		a
																				.search(
																						null,
																						c)
																	}
																},
																a.options.delay);
														break
													}
												}
											}).bind("keypress.autocomplete",
											function(c) {
												if (g) {
													g = false;
													c.preventDefault()
												}
											}).bind(
											"focus.autocomplete",
											function() {
												if (!a.options.disabled) {
													a.selectedItem = null;
													a.previous = a.element
															.val()
												}
											}).bind(
											"blur.autocomplete",
											function(c) {
												if (!a.options.disabled) {
													clearTimeout(a.searching);
													a.closing = setTimeout(
															function() {
																a.close(c);
																a._change(c)
															}, 150)
												}
											});
//							//console.log("Init source here");
							this._initSource();
							this.response = function() {
								return a._response.apply(a, arguments)
							};
							this.menu = d("<ul></ul>")
									.addClass("ui-autocomplete")
									.appendTo(
											d(this.options.appendTo || "body",
													b)[0])
									.mousedown(
											function(c) {
												var f = a.menu.element[0];
												d(c.target).closest(
														".ui-menu-item").length
														|| setTimeout(
																function() {
																	d(document)
																			.one(
																					"mousedown",
																					function(
																							h) {
																						h.target !== a.element[0]
																								&& h.target !== f
																								&& !d.ui
																										.contains(
																												f,
																												h.target)
																								&& a
																										.close()
																					})
																}, 1);
												setTimeout(function() {
													clearTimeout(a.closing)
												}, 13)
											})
									.menu(
											{
												focus : function(c, f) {
													f = f.item
															.data("item.autocomplete");
													false !== a._trigger(
															"focus", c, {
																item : f
															})
															&& /^key/
																	.test(c.originalEvent.type)
															&& a.element
																	.val(f.value)
												},
												selected : function(c, f) {
													var h = f.item
															.data("item.autocomplete"), i = a.previous;
													if (a.element[0] !== b.activeElement) {
														a.element.focus();
														a.previous = i;
														setTimeout(function() {
															a.previous = i;
															a.selectedItem = h
														}, 1)
													}
													false !== a._trigger(
															"select", c, {
																item : h
															})
															&& a.element
																	.val("");
													a.term = a.element.val();
													a.close(c);
													a.selectedItem = h
												},
												blur : function() {
													a.menu.element
															.is(":visible")
															&& a.element.val() !== a.term
															&& a.element
																	.val(a.term)
												}
											})
									.zIndex(this.element.zIndex() + 1).css({
										top : 0,
										left : 0
									}).hide().data("menu");
							d.fn.bgiframe && this.menu.element.bgiframe()
						},
						destroy : function() {
							this.element.removeClass("ui-autocomplete-input")
									.removeAttr("autocomplete").removeAttr(
											"role").removeAttr(
											"aria-autocomplete").removeAttr(
											"aria-haspopup");
							this.menu.element.remove();
							d.Widget.prototype.destroy.call(this)
						},
						_setOption : function(a, b) {
							d.Widget.prototype._setOption
									.apply(this, arguments);
							a === "source" && this._initSource();
							if (a === "appendTo")
								this.menu.element.appendTo(d(b || "body",
										this.element[0].ownerDocument)[0]);
							a === "disabled" && b && this.xhr
									&& this.xhr.abort()
						},
						_initSource : function() {
							var a = this, b, g;
//							console.log("_initSource");
//							console.log(this.options.source + "");
							if (d.isArray(this.options.source)) {
								b = this.options.source;
								this.source = function(c, f) {
//									console.log("dong anh");
//									console.log(f);
									f(d.ui.autocomplete.filter(b, c.term))
								}
							} else if (typeof this.options.source === "string") {
								g = this.options.source;
								this.source = function(c, f) {
									a.xhr && a.xhr.abort();
									a.xhr = d.ajax({
										url : g,
										data : c,
										dataType : "json",
										autocompleteRequest : ++e,
										success : function(h) {
											this.autocompleteRequest === e
													&& f(h)
										},
										error : function() {
											this.autocompleteRequest === e
													&& f([])
										}
									})
								}
							} else
								this.source = this.options.source
						},
						search : function(a, b) {
							a = a != null ? a : this.element.val();
							this.term = this.element.val();
							if (a.length < this.options.minLength)
								return this.close(b);
							clearTimeout(this.closing);
							if (this._trigger("search", b) !== false)
								return this._search(a)
						},
						_search : function(a) {
							this.pending++;
							this.element.addClass("ui-autocomplete-loading");
							this.source({
								term : a
							}, this.response)
						},
						_response : function(a) {
							if (!this.options.disabled && a && a.length) {
								a = this._normalize(a);
								this._suggest(a);
								this._trigger("open")
							} else
								this.close();
							this.pending--;
							this.pending
									|| this.element
											.removeClass("ui-autocomplete-loading")
						},
						close : function(a) {
							clearTimeout(this.closing);
							if (this.menu.element.is(":visible")) {
								this.menu.element.hide();
								this.menu.deactivate();
								this._trigger("close", a)
							}
						},
						_change : function(a) {
							this.previous !== this.element.val()
									&& this._trigger("change", a, {
										item : this.selectedItem
									})
						},
						_normalize : function(a) {
							if (a.length && a[0].label && a[0].value)
								return a;
							return d.map(a, function(b) {
								if (typeof b === "string")
									return {
										label : b,
										value : b
									};
								return d.extend({
									label : b.label || b.value,
									value : b.value || b.label
//									id: b.id || "Long"
								}, b)
							})
						},
						_suggest : function(a) {
							var b = this.menu.element.empty().zIndex(
									this.element.zIndex() + 1);
							this._renderMenu(b, a);
							this.menu.deactivate();
							this.menu.refresh();
							b.show();
							this._resizeMenu();
							b.position(d.extend({
								of : this.element
							}, this.options.position))
						},
						_resizeMenu : function() {
							var a = this.menu.element;
							a.outerWidth(Math.max(a.width("").outerWidth(),
									this.element.outerWidth()))
						},
						_renderMenu : function(a, b) {
							var g = this;
							d.each(b, function(c, f) {
								g._renderItem(a, f)
							})
						},
						_renderItem : function(a, b) {
							var label = b.label;
							var arr = label.split("##");
							var str = "<a></a>";
							var objParam = {};
							objParam.label = b.label;
							objParam.value = b.value;
							objParam.test = "default";
							if (b.value.search("i:")){
								str = '<a style="color:blue"></a>';
//								console.log(b.value);
							}
							
							
							var btn = "";
							if (arr.length == 2){
								str = "<a catch_id = '"+arr[1]+"' catch = '"+escape(arr[0])+"'class=ui-auto-item-expertise></a>";
								objParam.label = arr[0];
								objParam.value = arr[0];
								objParam.test = "expertise";
								btn = "<span class=ui-auto-item-expertise-label>Chuyên môn</span>";
							}
							if (arr.length > 2){
								objParam.label = arr[1];
								objParam.value = arr[1];
								objParam.test = "question";
								str = "<a question_id = '"+arr[0]+"' question = '"+escape(arr[1])+"'>";
								for (var i=2; i<arr.length-1; i++){
									btn += "<span class=ui-button-text>" + arr[i] + "</span>";
								}
								str += "</a>";
								//console.log(str);
							};
							return d("<li></li>").data("item.autocomplete", objParam)
									.append(d(str).text(objParam.label).append(d(btn)))
									.appendTo(a);
						},
						_move : function(a, b) {
							if (this.menu.element.is(":visible"))
								if (this.menu.first() && /^previous/.test(a)
										|| this.menu.last() && /^next/.test(a)) {
									this.element.val(this.term);
									this.menu.deactivate()
								} else
									this.menu[a](b);
							else
								this.search(null, b)
						},
						widget : function() {
							return this.menu.element
						}
					});
	d.extend(d.ui.autocomplete, {
		escapeRegex : function(a) {
			return a.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")
		},
		filter : function(a, b) {
			var g = new RegExp(d.ui.autocomplete.escapeRegex(b), "i");
			return d.grep(a, function(c) {
				return g.test(c.label || c.value || c)
			})
		}
	})
})(jQuery);
(function(d) {
	d
			.widget(
					"ui.menu",
					{
						_create : function() {
							var e = this;
							this.element
									.addClass(
											"ui-menu ui-widget ui-widget-content ui-corner-all")
									.attr(
											{
												role : "listbox",
												"aria-activedescendant" : "ui-active-menuitem"
											})
									.click(
											function(a) {
												if (d(a.target).closest(
														".ui-menu-item a").length) {
													a.preventDefault();
													e.select(a)
												}
											});
							this.refresh()
						},
						refresh : function() {
							var e = this;
							this.element.children(
									"li:not(.ui-menu-item):has(a)").addClass(
									"ui-menu-item").attr("role", "menuitem")
									.children("a").addClass("ui-corner-all")
									.attr("tabindex", -1).mouseenter(
											function(a) {
												e.activate(a, d(this).parent())
											}).mouseleave(function() {
										e.deactivate()
									})
						},
						activate : function(e, a) {
							this.deactivate();
							if (this.hasScroll()) {
								var b = a.offset().top
										- this.element.offset().top, g = this.element
										.attr("scrollTop"), c = this.element
										.height();
								if (b < 0)
									this.element.attr("scrollTop", g + b);
								else
									b >= c
											&& this.element.attr("scrollTop", g
													+ b - c + a.height())
							}
							this.active = a.eq(0).children("a").addClass(
									"ui-state-hover").attr("id",
									"ui-active-menuitem").end();
							this._trigger("focus", e, {
								item : a
							})
						},
						deactivate : function() {
							if (this.active) {
								this.active.children("a").removeClass(
										"ui-state-hover").removeAttr("id");
								this._trigger("blur");
								this.active = null
							}
						},
						next : function(e) {
							this.move("next", ".ui-menu-item:first", e)
						},
						previous : function(e) {
							this.move("prev", ".ui-menu-item:last", e)
						},
						first : function() {
							return this.active
									&& !this.active.prevAll(".ui-menu-item").length
						},
						last : function() {
							return this.active
									&& !this.active.nextAll(".ui-menu-item").length
						},
						move : function(e, a, b) {
							if (this.active) {
								e = this.active[e + "All"](".ui-menu-item").eq(
										0);
								e.length ? this.activate(b, e) : this.activate(
										b, this.element.children(a))
							} else
								this.activate(b, this.element.children(a))
						},
						nextPage : function(e) {
							if (this.hasScroll())
								if (!this.active || this.last())
									this.activate(e, this.element
											.children(".ui-menu-item:first"));
								else {
									var a = this.active.offset().top, b = this.element
											.height(), g = this.element
											.children(".ui-menu-item")
											.filter(
													function() {
														var c = d(this)
																.offset().top
																- a
																- b
																+ d(this)
																		.height();
														return c < 10
																&& c > -10
													});
									g.length
											|| (g = this.element
													.children(".ui-menu-item:last"));
									this.activate(e, g)
								}
							else
								this.activate(e, this.element.children(
										".ui-menu-item").filter(
										!this.active || this.last() ? ":first"
												: ":last"))
						},
						previousPage : function(e) {
							if (this.hasScroll())
								if (!this.active || this.first())
									this.activate(e, this.element
											.children(".ui-menu-item:last"));
								else {
									var a = this.active.offset().top, b = this.element
											.height();
									result = this.element.children(
											".ui-menu-item").filter(
											function() {
												var g = d(this).offset().top
														- a + b
														- d(this).height();
												return g < 10 && g > -10
											});
									result.length
											|| (result = this.element
													.children(".ui-menu-item:first"));
									this.activate(e, result)
								}
							else
								this.activate(e, this.element.children(
										".ui-menu-item").filter(
										!this.active || this.first() ? ":last"
												: ":first"))
						},
						hasScroll : function() {
							return this.element.height() < this.element
									.attr("scrollHeight")
						},
						select : function(e) {
							this._trigger("selected", e, {
								item : this.active
							})
						}
					})
})(jQuery);;

/**
 * TextAreaExpander plugin for jQuery
 * v1.0
 * Expands or contracts a textarea height depending on the
 * quatity of content entered by the user in the box.
 *
 * By Craig Buckler, Optimalworks.net
 *
 * As featured on SitePoint.com:
 * http://www.sitepoint.com/blogs/2009/07/29/build-auto-expanding-textarea-1/
 *
 * Please use as you wish at your own risk.
 */

/**
 * Usage:
 *
 * From JavaScript, use:
 *     $(<node>).TextAreaExpander(<minHeight>, <maxHeight>);
 *     where:
 *       <node> is the DOM node selector, e.g. "textarea"
 *       <minHeight> is the minimum textarea height in pixels (optional)
 *       <maxHeight> is the maximum textarea height in pixels (optional)
 *
 * Alternatively, in you HTML:
 *     Assign a class of "expand" to any <textarea> tag.
 *     e.g. <textarea name="textarea1" rows="3" cols="40" class="expand"></textarea>
 *
 *     Or assign a class of "expandMIN-MAX" to set the <textarea> minimum and maximum height.
 *     e.g. <textarea name="textarea1" rows="3" cols="40" class="expand50-200"></textarea>
 *     The textarea will use an appropriate height between 50 and 200 pixels.
 */

(function($) {

	// jQuery plugin definition
	$.fn.TextAreaExpander = function(minHeight, maxHeight) {

		var hCheck = !($.browser.msie || $.browser.opera);

		// resize a textarea
		function ResizeTextarea(e) {

			// event or initialize element?
			e = e.target || e;

			// find content length and box width
			var vlen = e.value.length, ewidth = e.offsetWidth;
			if (vlen != e.valLength || ewidth != e.boxWidth) {
				if (hCheck && (vlen < e.valLength || ewidth != e.boxWidth))	{
					e.style.height = "0px";
				}
				//console.log(e.expandMin);
				var h = Math.max(e.expandMin, Math.min(e.scrollHeight, e.expandMax));

				e.style.overflow = (e.scrollHeight > h ? "auto" : "hidden");
				e.style.height = h + "px";

				e.valLength = vlen;
				e.boxWidth = ewidth;
			}

			return true;
		};

		// initialize
		this.each(function() {

			// is a textarea?
			if (this.nodeName.toLowerCase() != "textarea") return;

			// set height restrictions
			var p = this.className.match(/expandable(\d+)\-*(\d+)*/i);
			this.expandMin = minHeight || (p ? parseInt('0'+p[1], 10) : 0);
			this.expandMax = maxHeight || (p ? parseInt('0'+p[2], 10) : 99999);

			// initial resize
			ResizeTextarea(this);

			// zero vertical padding and add events
			if (!this.Initialized) {
				this.Initialized = true;
				$(this).css("padding-top", 0).css("padding-bottom", 0);
				$(this).bind("keyup", ResizeTextarea).bind("focus", ResizeTextarea);
			}
		});

		return this;
	};

})(jQuery);


// initialize all expanding textareas
jQuery(document).ready(function() {
	jQuery("textarea[class*=expandable]").TextAreaExpander();
});

/*
 * Facebox (for jQuery)
 * version: 1.2 (05/05/2008)
 * @requires jQuery v1.2 or later
 *
 * Examples at http://famspam.com/facebox/
 *
 * Licensed under the MIT:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright 2007, 2008 Chris Wanstrath [ chris@ozmm.org ]
 *
 * Usage:
 *  
 *  jQuery(document).ready(function() {
 *    jQuery('a[rel*=facebox]').facebox() 
 *  })
 *
 *  <a href="#terms" rel="facebox">Terms</a>
 *    Loads the #terms div in the box
 *
 *  <a href="terms.html" rel="facebox">Terms</a>
 *    Loads the terms.html page in the box
 *
 *  <a href="terms.png" rel="facebox">Terms</a>
 *    Loads the terms.png image in the box
 *
 *
 *  You can also use it programmatically:
 * 
 *    jQuery.facebox('some html')
 *
 *  The above will open a facebox with "some html" as the content.
 *    
 *    jQuery.facebox(function($) { 
 *      $.get('blah.html', function(data) { $.facebox(data) })
 *    })
 *
 *  The above will show a loading screen before the passed function is called,
 *  allowing for a better ajaxy experience.
 *
 *  The facebox function can also display an ajax page or image:
 *  
 *    jQuery.facebox({ ajax: 'remote.html' })
 *    jQuery.facebox({ image: 'dude.jpg' })
 *
 *  Want to close the facebox?  Trigger the 'close.facebox' document event:
 *
 *    jQuery(document).trigger('close.facebox')
 *
 *  Facebox also has a bunch of other hooks:
 *
 *    loading.facebox
 *    beforeReveal.facebox
 *    reveal.facebox (aliased as 'afterReveal.facebox')
 *    init.facebox
 *
 *  Simply bind a function to any of these hooks:
 *
 *   $(document).bind('reveal.facebox', function() { ...stuff to do after the facebox and contents are revealed... })
 *
 */
(function($) {
  $.facebox = function(data, klass) {
    $.facebox.loading();

    if (data.ajax) fillFaceboxFromAjax(data.ajax);
    else if (data.image) fillFaceboxFromImage(data.image);
    else if (data.div) fillFaceboxFromHref(data.div);
    else if ($.isFunction(data)) data.call($);
    else $.facebox.reveal(data, klass);
  }
  
  /*
   * Public, $.facebox methods
   */
  
  $.extend($.facebox, {
    settings: {
      opacity      : 0,
      overlay      : true,
      loadingImage : ''+'/static/css/loading.gif',
      closeImage   : ''+'/static/css/closelabel.gif',
      imageTypes   : [ 'png', 'jpg', 'jpeg', 'gif' ],
      faceboxHtml  : '\
    <div id="facebox" style="display:none;"> \
      <div class="popup"> \
        <table> \
          <tbody> \
            <tr> \
              <td class="tl"/><td class="b"/><td class="tr"/> \
            </tr> \
            <tr> \
              <td class="b"/> \
              <td class="body"> \
                <div class="content"> \
                </div> \
                <div class="footer"> \
                  <a href="#" class="close"> \
                    <img src="/static/includes/facebox/closelabel.gif" title="close" class="close_image" /> \
                  </a> \
                </div> \
              </td> \
              <td class="b"/> \
            </tr> \
            <tr> \
              <td class="bl"/><td class="b"/><td class="br"/> \
            </tr> \
          </tbody> \
        </table> \
      </div> \
    </div>'
    },

    loading: function() {
      init();
      if ($('#facebox .loading').length == 1) return true
      showOverlay();

      $('#facebox .content').empty()
      $('#facebox .body').children().hide().end().
        append('<div class="loading"><img src="'+$.facebox.settings.loadingImage+'"/></div>');

      $('#facebox').css({
        top:	getPageScroll()[1] + (getPageHeight() / 10),
        left:	385.5
      }).show();

      $(document).bind('keydown.facebox', function(e) {
        if (e.keyCode == 27)	{
        	$.facebox.close();
        }
        return true;
      })
      $(document).trigger('loading.facebox')
    },

    reveal: function(data, klass) {
      $(document).trigger('beforeReveal.facebox')
      if (klass) $('#facebox .content').addClass(klass)
      $('#facebox .content').append(data)
      $('#facebox .loading').remove()
      $('#facebox .body').children().fadeIn('normal')
      $('#facebox').css('left', $(window).width() / 2 - ($('#facebox table').width() / 2))
      $(document).trigger('reveal.facebox').trigger('afterReveal.facebox')
    },

    close: function() {
      $(document).trigger('close.facebox')
      return false
    }
  })

  /*
   * Public, $.fn methods
   */

  $.fn.facebox = function(settings) {
    init(settings)

    function clickHandler() {
      $.facebox.loading(true)

      // support for rel="facebox.inline_popup" syntax, to add a class
      // also supports deprecated "facebox[.inline_popup]" syntax
      var klass = this.rel.match(/facebox\[?\.(\w+)\]?/)
      if (klass) klass = klass[1]

      fillFaceboxFromHref(this.href, klass)
      return false
    }

    return this.click(clickHandler)
  }

  /*
   * Private methods
   */

  // called one time to setup facebox on this page
  function init(settings) {
    if ($.facebox.settings.inited) return true
    else $.facebox.settings.inited = true

    $(document).trigger('init.facebox')
    makeCompatible()

    var imageTypes = $.facebox.settings.imageTypes.join('|')
    $.facebox.settings.imageTypesRegexp = new RegExp('\.' + imageTypes + '$', 'i')

    if (settings) $.extend($.facebox.settings, settings)
    $('body').append($.facebox.settings.faceboxHtml)

    var preload = [ new Image(), new Image() ]
    preload[0].src = $.facebox.settings.closeImage
    preload[1].src = $.facebox.settings.loadingImage

    $('#facebox').find('.b:first, .bl, .br, .tl, .tr').each(function() {
      preload.push(new Image())
      preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1')
    })

    $('#facebox .close').click($.facebox.close)
    $('#facebox .close_image').attr('src', $.facebox.settings.closeImage)
  }
  
  // getPageScroll() by quirksmode.com
  function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;	
    }
    return new Array(xScroll,yScroll) 
  }

  // Adapted from getPageSize() by quirksmode.com
  function getPageHeight() {
    var windowHeight
    if (self.innerHeight) {	// all except Explorer
      windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
      windowHeight = document.body.clientHeight;
    }	
    return windowHeight
  }

  // Backwards compatibility
  function makeCompatible() {
    var $s = $.facebox.settings

    $s.loadingImage = $s.loading_image || $s.loadingImage
    $s.closeImage = $s.close_image || $s.closeImage
    $s.imageTypes = $s.image_types || $s.imageTypes
    $s.faceboxHtml = $s.facebox_html || $s.faceboxHtml
  }

  // Figures out what you want to display and displays it
  // formats are:
  //     div: #id
  //   image: blah.extension
  //    ajax: anything else
  function fillFaceboxFromHref(href, klass) {
    // div
    if (href.match(/#/)) {
      var url    = window.location.href.split('#')[0]
      var target = href.replace(url,'')
      $.facebox.reveal($(target).clone().show(), klass)

    // image
    } else if (href.match($.facebox.settings.imageTypesRegexp)) {
      fillFaceboxFromImage(href, klass)
    // ajax
    } else {
      fillFaceboxFromAjax(href, klass)
    }
  }

  function fillFaceboxFromImage(href, klass) {
    var image = new Image()
    image.onload = function() {
      $.facebox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass)
    }
    image.src = href
  }

  function fillFaceboxFromAjax(href, klass) {
    $.get(href, function(data) { $.facebox.reveal(data, klass) })
  }

  function skipOverlay() {
    return $.facebox.settings.overlay == false || $.facebox.settings.opacity === null 
  }

  function showOverlay() {
    if (skipOverlay()) return

    if ($('facebox_overlay').length == 0) 
      $("body").append('<div id="facebox_overlay" class="facebox_hide"></div>')

    $('#facebox_overlay').hide().addClass("facebox_overlayBG")
      .css('opacity', $.facebox.settings.opacity)
      .click(function() { $(document).trigger('close.facebox') })
      .fadeIn(200)
    return false
  }

  function hideOverlay() {
    if (skipOverlay()) return

    $('#facebox_overlay').fadeOut(200, function(){
      $("#facebox_overlay").removeClass("facebox_overlayBG")
      $("#facebox_overlay").addClass("facebox_hide") 
      $("#facebox_overlay").remove()
    })
    
    return false
  }

  /*
   * Bindings
   */

  $(document).bind('close.facebox', function() {
    $(document).unbind('keydown.facebox')
    $('#facebox').fadeOut(function() {
      $('#facebox .content').removeClass().addClass('content')
      hideOverlay()
      $('#facebox .loading').remove()
    })
  })

})(jQuery);

(function($) {
    
    $.timeFormat = function( timestamp ) {
        var time = handleDate( timestamp, extractDateHour );
        return time;
    };
    
    $.timeFormatSolr = function ( timestamp )	{
    	var time = handleDate( timestamp, extractDateHourSolr );
    	return time;
    };
    
    function extractDateHourSolr(timestamp)	{
    	var arr = timestamp.split(' ');
    	var d = arr[1].split('/');
    	var h = arr[0].split(':');
    	var timestamp = Date.UTC(d[2],d[1]-1,d[0],h[0],h[1],0,0)/1000;
    	return timestamp;
    }
    
    function extractDateHour(timestamp)	{
    	var arr = timestamp.split(' ');
    	var d = arr[0].split('-');
    	var h = arr[1].split(':');
    	var timestamp = Date.UTC(d[0],d[1]-1,d[2],h[0],h[1],h[2],0)/1000;
    	return timestamp;
    }
    
    function handleDate( timestamp, func ) {
        var n=new Date(), t, ago = " ";
        if( timestamp ) {
        	var timestamp = func(timestamp);
        	//420 min = UTC+7
        	t =   Math.round( (n.getTime()/1000 - timestamp)/60 + 420 );
        	ago += handleSinceDateEndings( t, timestamp );
        } else {
            ago += "";
        }
        return ago;
    }
    
    function handleSinceDateEndings( t, original_timestamp ) {
        var ago = " ", date;
        date = new Date( parseInt( original_timestamp )*1000 );
        if( t <= 1 ) {
            ago += "Vài giây trước";
        } else if( t<60) {
            ago += t + " phút trước";
        } else if( t>= 60 && t<= 120) {
            ago += Math.floor( t / 60 ) + " giờ trước";
        } else if( t<1440 ) {
            ago += Math.floor( t / 60 )  + " giờ trước";
        } else if( t< 2880) {
            ago +=  "1 ngày trước lúc "+ date.getUTCHours()+'h:'+date.getUTCMinutes();
        } else if( t > 2880  && t < 4320 ) {
            ago +=  "2 ngày trước lúc "+ date.getUTCHours()+'h:'+date.getUTCMinutes();
        } else {
            ago += "ngày " + date.getDate() + "/" + months[ date.getMonth() ] + "/"+ (1900+date.getYear()) +" lúc "+ date.getUTCHours()+'h:'+date.getUTCMinutes();
        }
        return ago;
    }
    
    var months = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"];
})(jQuery);

jQuery.slugify = function(txt) {
	txt = removeAccents(txt.toLowerCase());
	txt = txt.replace(/\s+/g,'-');
	txt = txt.replace(/[^a-zA-Z0-9\-]/g,'').trim('-');
	return txt;
}

function removeAccents(str){
	//remove accented, perhaps there are other simple ways
    str = str.replace(/[áàảãạăắằẳẵặâấầẩẫậ]/g, 'a');
    str = str.replace(/đ/g, 'd');
    str = str.replace(/[éèẻẽẹêếềểễệ]/g, 'e');
    str = str.replace(/[íìỉĩị]/g, 'i');
    str = str.replace(/[óòỏõọôốồổỗộơớờởỡợ]/g, 'o');
    str = str.replace(/[úùủũụưứừửữự]/g, 'u');
    str = str.replace(/[ýỳỷỹỵ]/g, 'y');
    return str;
}
/**
 * A class to store system-wide properties
 * @augments Class
 * @author griever
 */
SystemProperty = Class.extend({
	
	/**
	 * Initialize properties
	 * @constructors
	 */
	init: function()	{
		this.properties = Array();
	},
	
	/**
	 * Retrieve the value of a property
	 * @function
	 * @param {property} the name of the property to retrieve
	 * @param {defaultValue} the default value, used if the property is not found
	 * @returns {mixed} the property value, or the default value or undefined 
	 */
	get: function(property, defaultValue)	{
		var cookieValue = $.cookie(property);
		if(cookieValue != undefined){
			return cookieValue;
		}else if(this.properties[property] != undefined){
			return this.properties[property];
		}else {
			return defaultValue;
		}
	},
	
	/**
	 * Store the value of a property
	 * @function
	 * @param {property} the name of the property to store
	 * @param {value} the new value
	 * @param {persistent} should the property be stored in cookie for future use
	 */
	set: function(property, value, persistent)	{
		if(!persistent){
			this.properties[property] = value;
		}else{
			$.cookie(property,value,{ expires: 1 });
		}
//		console.log('system property changed: '+property);
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent("SystemPropertyChanged", property);
	},
	
	dump: function()	{
		//console.log('Dumping system properties...');
		for(var p in this.properties)	{
			//console.log(p+": "+this.properties[p]);
		}
		//console.log('Dumping complete!');
	}
});

/**
 * Resource Manager. Manage resource using the underlying resource locator
 * @augments Class
 * @author griever
 */
ResourceManager = Class.extend({
	
	/**
	 * Initialize resource locators
	 * @constructors
	 */
	init: function()	{
		this.resourceLocator = new JQueryResourceLocator();
	},
	
	/**
	 * Change the current resource locator
	 * @param {locator} the resource locator to be used
	 */
	setResourceLocator: function(locator)	{
		this.resourceLocator = locator;
	},
	
	/**
	 * Get the current resource locator
	 * @returns {ResourceLocator} the current resource locator
	 */
	getResourceLocator: function(locator)	{
		return this.resourceLocator;
	},
	
	/**
	 * Ask the underlying resource locator for a specific resource
	 * @param {type} used as a namespace to distinct different resources with the same name
	 * @param {name} the name of the resource
	 * @param {resourceLocator} Optional. The resource locator to be used in the current request
	 */
	requestForResource: function(type, name, resourceLocator)	{
		var id = type+"-"+name;
		if (resourceLocator != undefined)	{
			return resourceLocator.locateResource(id);
		}
		return this.resourceLocator.locateResource(id);
	},
	
	/**
	 * Ask the underlying resource locator for a custom resource
	 * @param {customSelector} the selector used to retrieve the resource, depending on underlying the resource locator
	 * @param {resourceLocator} Optional. The resource locator to be used in the current request
	 */
	requestForCustomResource: function(customSelector, resourceLocator)	{
		if (resourceLocator != undefined)	{
			return resourceLocator.locateResource(customSelector);
		}
		return this.resourceLocator.locateCustomResource(customSelector);
	}
});

/**
 * ResourceLocator. Locate resource
 * @augments Class
 * @author griever
 */
ResourceLocator = Class.extend({
	/**
	 * Locate a resource based on its ID
	 * By default, this function do nothing
	 */
	locateResource: function(resourceID)	{
		
	}
});

/**
 * JQuery Resource Locator. Locate resource using DOM
 * @augments ResourceLocator
 * @author griever
 */
JQueryResourceLocator = ResourceLocator.extend({
	
	/**
	 * Locate resource based on its ID
	 * @param {id} the resource ID
	 * @returns {mixed} the resource or undefined
	 */
	locateResource: function(id)	{
		if ($('#'+id).length > 0)	{
			return $('#'+id);
		}
		return undefined;
	},
	
	/**
	 * Locate resource based on the custom selector
	 * @param {custom} the custom selector
	 * @returns {mixed} the resource or undefined
	 */
	locateCustomResource: function(custom)	{
		if ($(custom).length > 0)	{
			return $(custom);
		}
		return undefined;
	}
});

//JQuery Horizontal alignment plugin
(function ($) { $.fn.vAlign = function() { return this.each(function(i){ var h = $(this).height(); var oh = $(this).outerHeight(); var mt = (h + (oh - h)) / 2; $(this).css("margin-top", "-" + mt + "px"); $(this).css("top", "50%"); $(this).css("position", "absolute"); }); }; })(jQuery); (function ($) { $.fn.hAlign = function() { return this.each(function(i){ var w = $(this).width(); var ow = $(this).outerWidth(); var ml = (w + (ow - w)) / 2; $(this).css("margin-left", "-" + ml + "px"); $(this).css("left", "50%"); $(this).css("position", "absolute"); }); }; })(jQuery);

/**
 * Manage a set of objects
 * @augments Class
 * @author griever
 */
ObjectManager = Class.extend({
	
	/**
	 * Initialize fields
	 * @constructor
	 */
	init: function()	{
		this.objects = new Array();
		this.context = null;
		this.mainObjects = new Array();
	},

	/**
	 * Register an object to be managed by this
	 * @function
	 * @param {obj} the object to register
	 */
	register: function(obj)	{
		this.objects.push(obj);
	},
	
	/**
	 * Register a context
	 * @function
	 * @param {obj} the context to register
	 */
	registerContext: function(obj)	{
		this.context = obj;
	},
	
	/**
	 * main object is one visualize the idea, a main object usually is a collection of main image
	 * and other thing support for the display
	 * @function
	 * @param {obj} the main object
	 */
	registerMainObjects: function(obj)	{
		this.mainObjects.push(obj);
	},
	
	/**
	 * Retrieve the main objects
	 * @function
	 * @returns {mixed} the main objects
	 */
	getMainObjects: function(){
		return this.mainObjects;
	},

	/**
	 * Remove object from the list
	 * @function
	 * @param {obj} the object to be removed
	 */
	remove: function(obj)	{
		/*
		* remove from display
		*/
		var i = this.findIndex(obj.id);
		if (i != -1)	{
			this.objects.splice(i, 1);
		}
		/*
		* remove from mainObjects array
		*/
		for(var j=0;j<this.mainObjects.length;j++)	{
			if(obj.id == this.mainObjects[j].id)		{
				this.mainObjects.splice(j,1);
			}
		}
	},
	
	/**
	 * Find an object using its ID
	 * @function
	 * @param {objId} the id of the object to be found
	 * @returns {mixed} the object or undefined
	 */
	find: function(objId)	{
		var i = this.findIndex(objId);
		if (i == -1)
			return undefined;
		return this.objects[i];
	},
	
	/**
	 * Find the index of the object having specific ID
	 * @function
	 * @param {objId} the id of the object to be found
	 * @returns {mixed} the index of the object or -1
	 */
	findIndex: function(objId)	{
		for(var i=0;i<this.objects.length;i++)	{
			if (objId == this.objects[i].id)	{
				return i;
			}
		}
		return -1;
	}
});

/**
 * Entry-point class
 * @augments Class
 */
Application = Class.extend({
	/**
	 * Initialize fields
	 * @constructor
	 */
	init: function()	{
		if(Application.singleton == undefined){
			throw "Singleton class, can not be directly created !";
			return undefined;
		}
		this.systemProperties = new SystemProperty();
		this.resourceManager = new ResourceManager();
	},
	
	/**
	 * Access the application's resource manager
	 * @function
	 * @returns {mixed} the application's resource manager
	 */
	getResourceManager: function()	{
		return this.resourceManager;
	},
	
	/**
	 * Change the application's resource manager
	 * @function
	 * @param {ResourceManager} the resource manager to be used
	 */
	setResourceManager: function(rm)	{
		this.resourceManager = rm;
	},
	
	/**
	 * Get the system properties array
	 * @function
	 * @returns {mixed} the system properties
	 */
	getSystemProperties: function()	{
		return this.systemProperties;
	},
	
	/**
	 * Change the bootstrap of the application
	 * @function
	 * @returns {Bootstrap} the bootstrap of the application
	 */
	setBootstrap: function(bootstrap)	{
		this.bootstrap = bootstrap;
	},

	/**
	 * Begin the application. This should be called only once
	 * @function
	 */
	begin: function()	{
		this.bootstrap.run();
	},

	/**
	 * Get the application's object manager
	 * @function
	 * @returns {ObjectManager} the application's object manager
	 */
	getObjectManager: function()	{
		if (this.objMgr == undefined)
			this.objMgr = new ObjectManager();
		return this.objMgr;
	}
});

/**
 * Singleton Factory. Used to access initialize
 */
SingletonFactory = function(){};

SingletonFactory.getInstance = function(classname){
	if(classname.instance == undefined){
		classname.singleton = 0;
		classname.instance = new classname();
		classname.singleton = undefined;
	}
	return classname.instance;
}

/**
 * IMPLEMENTOR & HANDLERS
 */
InterfaceImplementor = Class.extend({
	init: function(){
		this.state = false;
	},

	implement: function(obj)	{
		
	},

	bind: function(obj, handler)	{
		new EventBinder().bindEvent(obj, handler);
	}
});

Handler = Class.extend({
	init: function(){
		
	},
	
	getEventName: function()	{
		return "";
	},
	
	onEvent: function(e)	{
		
	}
});

/**
 * Wrap the jquery object with our DisplayObject
 * In the future it will add classes, bind events... as well
 */
JQueryWrapper = Class.extend({
	init: function(obj, id)	{
		obj.id = id;
		this.obj = obj;
	},
	
	getWrappedObject: function()	{
		return this.obj;
	}
});
/**
 * Base displayable object
 */
DisplayObject = Class.extend	({
	init: function()	{
		var app = SingletonFactory.getInstance(Application);
		this.id=0;
		this.type = "default";
		this.htmlClasses = new Array();
		this.interfaces = new Array();
		var objMgr = app.getObjectManager();
		this.className = "DisplayObject";
		objMgr.register(this);
	},
	
	addEventHandler: function(eventHandler)	{
		new EventBinder().bindEvent(this, eventHandler);
	},
	
	deserializeStyle: function(style)	{
		this.deserializedStyle = style;
	},
	
	serializeStyle: function()	{
		return this.getAttribute('style');
	},
	
	serialize: function()	{
		var obj = {};
		obj.className = this.className;
		return obj;
	},
	
	getPosition: function()	{
		return this.access().offset();
	},
	
	moveTo: function(top, left)	{
		this.access().css('left', left+"px");
		this.access().css('top', top+"px");
	},
	
	center: function()	{
		this.access().hAlign();
		this.access().vAlign();
	},
	
	moveToBR: function(bottom, right)	{
		this.access().css('bottom', bottom+"px");
		this.access().css('right', right+"px");
	},

	getType: function()	{
		return "ij-"+this.type;
	},

	toHtml: function()	{
		return "";
	},
	
	getParent: function()	{
		return this.parent;
	},
	
	setParent: function(parent)	{
		if (this.parent != undefined)	{
			this.parent.detachObject(this);
		}
		this.parent = parent;
	},
	
	getId: function()	{
		return this.id;
	},
	
	access: function()	{
		return $('#'+this.id);
	},
	
	resizeTo: function(width, height)	{
		this.access().css('width', width+"px");
		this.access().css('height', height+"px");
	},
	
	getDimension: function()	{
		var dim = {};
		dim.width = this.access().width();
		dim.height = this.access().height();
		return dim;
	},
	
	setStyle: function(styleName, value)	{
		this.access().css(styleName, value);
	},
	
	setAttribute: function(attrName, value)	{
		this.access().attr(attrName, value);
	},
	
	getAttribute: function(attrName)	{
		return this.access().attr(attrName);
	},
	
	implement: function(implementor)	{
		if($("#"+this.getId()).length > 0){
			implementor.implement(this);
			implementor.state = true;
		}
		this.interfaces.push(implementor);
		this.updateInterfaces();
	},
	
	addClass: function(className)	{
		this.htmlClasses.push(className);
		this.updateClasses();
	},
	
	getHtmlClasses: function()	{
		return this.htmlClasses;
	},
	
	show: function()	{
		this.access().show();
	},
	
	hide: function()	{
		this.access().hide();
	},
	
	dispose: function()	{
		var app = SingletonFactory.getInstance(Application);
		this.access().remove();
		app.getObjectManager().remove(this);
	},
	
	updateClasses: function()	{
		var classes = this.getHtmlClasses();
		var classNames = this.getType();
		for(var i=0;i<classes.length;i++)	{
			classNames+= " "+classes[i];
		}
		this.access().attr('class', classNames);
	},
	
	updateInterfaces: function()	{
		var interfaces = this.interfaces;
		for(var i=0;i<interfaces.length;i++)	{
			var implementor = interfaces[i];
			if (implementor != null && !implementor.state && $("#"+this.getId()).length > 0)	{
				implementor.implement(this);
				implementor.state = true;
			}
		}
	},
	
	afterLoad: function()	{
		this.setAttribute('style', this.deserializedStyle);
	},
	
	/**
	 * Update HTML element when properties are changed
	 */
	update: function()	{
		this.updateClasses();
		this.updateInterfaces();
	},
	
	afterCreate: function()	{
		this.update();
		new EventBinder().fireEvent(this.access(), 'object_created');
	}
});

/**
 * Container class. A container is an object which 'contains' other objects
 */
Container = DisplayObject.extend({
	init: function()	{
		this._super();
		this.objects = new Array();
		this.type = "container";
		this.className = "Container";
	},
	
	addObjectBeforePosition: function(obj, positionObj)	{
		this.objects.push(obj);
		//this.access().append(obj.toHtml());
		if($("#"+obj.access().attr("id")).length == 0){
			//console.log("Not existed before !, id: "+obj.access().attr("id"));
			$(positionObj).before(obj.toHtml());
		}else{
			//console.log("Just move !");
			obj.access().detach();
			obj.access().insertBefore(positionObj);
		}
		obj.setParent(this);
		obj.afterCreate();
	},
	
	addObject: function(obj)	{
		this.objects.push(obj);
		//this.access().append(obj.toHtml());
		if($("#"+obj.access().attr("id")).length == 0){
			//console.log("Not existed before !, id: "+obj.access().attr("id"));
			this.access().append(obj.toHtml());
		}else{
			//console.log("Just move !");
			obj.access().detach();
			obj.access().appendTo(this.access());
		}
		obj.setParent(this);
		obj.afterCreate();
	},
	
	afterCreate: function(obj)	{
		this._super();
		for(var i=0;i<this.objects.length;i++)	{
			this.objects[i].afterCreate();
		}
	},
	
	removeObject: function(object)	{
		for(var i=0;i<this.objects.length;i++)	{
			var obj = this.objects[i];
			if (obj.getId() == object.getId())	{
				this.objects.splice(i, 1);
				object.dispose();
			}
		}
	},
	
	detachObject: function(object)	{
		for(var i=0;i<this.objects.length;i++)	{
			var obj = this.objects[i];
			if (obj.getId() == object.getId())	{
				this.objects.splice(i, 1);
			}
		}
	},
	
	getObjects: function()	{
		return this.objects;
	},
	
	toHtml: function()	{
		var html = "";
		for(var i=0;i<this.objects.length;i++)	{
			html += this.objects[i].toHtml();
		}
		return html;
	}
});

Canvas = Container.extend({
	init: function()	{
		this._super();
		// FIXME: Store this list in another location?
		this.type = "canvas";
		this.id = generateId('canvas');
		this.className = "Canvas";
	},

	toHtml: function()	{
		return "<div id='"+this.id+"'>"+this._super()+"</div>";
	}
});

PrebuiltCanvas = Canvas.extend({
	init: function(id)	{
		this._super();
		this.id = id;
	},
	
	appendObject: function(object)	{
		this.access().append(object.access());
	}
});

/*
 * Font
 */
Font = Class.extend({
	init:function()	{
		this.fontFamily = 'Tahoma,sans-serif';
		this.fontSize = "12px";
		this.bold = false;
		this.italic = false;
		this.color = "#000000";
	},
	
	setFont: function(fontFamily, fontSize, bold, italic, color)	{
		this.fontFamily = fontFamily;
		this.fontSize = fontSize;
		this.bold = bold;
		this.italic = italic;
		this.color = color;
	},
	
	setFontFamily: function(fontFamily)	{
		this.fontFamily = fontFamily;
	},
	
	getFontFamily: function()	{
		return this.fontFamily;
	},
	
	setFontSize: function(fontSize)	{
		this.fontSize = fontSize;
	},
	
	getFontSize: function()	{
		return this.fontSize;
	},
	
	setBold: function(bold)	{
		this.bold = bold;
	},
	
	getBold: function()	{
		return this.bold;
	},
	
	setItalic: function(italic)	{
		this.italic = italic;
	},
	
	getItalic: function()	{
		return this.italic;
	},
	
	setColor: function(color)	{
		this.color = color;
	},
	
	getColor: function()	{
		return this.color;
	}
});
/**
 * Image object
 */
ImageObject = DisplayObject.extend	({
	
	init: function(src)	{
		this._super();
		if (!src.match("http://") && !src.match("https://")){
			config = new Config();
			this.src = config.getRoot()+src;
		}else{
			this.src = src;
		}
		this.id = generateId('image');
		this.type = "Image";
		this.zIndex = 1000;
		this.className = "ImageObject";
	},
	
	toHtml: function()	{
		return "<img id='"+this.id+"' src='"+this.src+"' ></img>";
	},
	
	getSrc: function()	{
		return this.src;
	}
});

/**
 * Rotatable
 */
RotatableImage = ImageObject.extend({
	init: function(src)	{
		this._super(src);
		this.prevrotation = 0;
		this.className = "RotatableImage";
	},
	
	setPrevRotation: function(rot){
		if (rot > 180){
			rot = rot - 180;
		}
		if (rot < -180){
			rot = rot + 180;
		}
		this.prevrotation = rot;
	},
	
	getPrevRotation: function(){
		return this.prevrotation;
	},
	
	rotate: function(e)	{
		var parent = this.getParent();
		var left = this.getPosition().left;
		var top = this.getPosition().top;
		
		var h = top - parent.baseDotTL.getPosition().top - 7;
		var w = left - parent.baseDotTL.getPosition().left - 7;
		
		var rad = Math.atan2(h, w);
		var deg = Math.round(rad*180/Math.PI);
		parent.access().css('-moz-transform', 'rotate('+deg+'deg)');
		parent.access().css('-webkit-transform', 'rotate('+deg+'deg)');
		parent.access().css('transform', 'rotate('+deg+'deg)');
	}
});


/**
 * Textbox
 */
TextArea = DisplayObject.extend	({
	
	init: function(txt)	{
		this._super();
		this.font = new Font();
		this.txt = txt;
		this.id = generateId('textarea');
		this.type = "TextArea";
		this.implement(new ClickTextAreaStopEvent());
		this.implement(new BlurTextAreaUpdate());
		this.className = "TextArea";
	},
	
	toHtml: function()	{
		return "<textarea id='"+this.id+"' value='"+this.txt+"'></textarea>";
	},
		
	getText: function()	{
		return this.access().val();
	},
	
	getFont: function(){
		return this.font;
	},
	
	setFont: function(font){
		this.font = font;
	},
	
	updateText: function()	{
		this.parent.updateText(this.getText(),this.getFont());
		this.hide();
	},
	
	focus: function()	{
		this.access().focus();
	}
});

/**
 * Label
 */
Label = DisplayObject.extend	({
	
	init: function(txt)	{
		this._super();
		this.txt = txt;
		this.id = generateId('text');
		this.type = "Label";
		this.className = "Label";
	},
	
	toHtml: function()	{
		return "<label id='"+this.id+"' value='"+this.txt+"'></label>";
	},
		
	getText: function()	{
		return this.access().html();
	},
	
	setText: function(txt,font)	{
		if(font==null){
			this.access().html(txt);
		}else{
			var text = txt;
			var fontText = "font-family: "+font.getFontFamily()+"; font-size:"+font.getFontSize();
			fontText += "; color:"+font.getColor();
			if(font.getItalic()){
				fontText += ";font-style:italic";
			}else{
				fontText += ";font-style:normal";
			}
			if(font.getBold()){
				fontText += ";font-weight:bold";
			}
			text = "<span style='"+fontText+"'>"+text+"</span>";
			this.access().html(text);
		}
	}
});

/*
* ContextMenu class. A context menu is trigger by the right click, holding many contextMenuItem
*/
ContextMenu = Canvas.extend({
	init: function()	{
		this._super();
		this.items = new Array();
		this.type = 'contextmenu';
		this.className = "ContextMenu";
	},
	
	addItem: function(item){
		this.items.push(item);
		this.addObject(item);
		this.update();
	},
	
	afterCreate: function(){
		this._super();
		this.setStyle('zIndex','1000');
		this.update();
	}
});

/*
* ContextMenuItem class. A context menu item is an item binding to events
*/
ContextMenuItem = Canvas.extend({
	init: function(lbl,obj)	{
		this._super();
		this.label_txt = lbl;
		this.label = new Label('');
		this.addObject(this.label);		
		this.type = "contextmenuitem";
		this.originObject = obj;
		this.className = "ContextMenuItem";
	},
	
	afterCreate: function(){
		this.label.setText(this.label_txt);
		this.update();
	},
	
	setOriginObject: function(obj)	{
		this.originObject = obj;
	},
	
	getOriginObject: function()	{
		return this.originObject;
	}
});

DraggableWrapper = Class.extend({
	wrap: function(obj)	{
		obj.access().draggable();
		obj.access().css('position','absolute');
		return obj;
	}
});

ImageIconWrapper = Class.extend	({
	wrap: function(img)	{
		img.addClass("icon");
		return img;
	}
});

ClickableImageWrapper = Class.extend({
	wrap: function(img)	{
		img.implement(new ClickIcon());
		return img;
	}
});

ImageBox = Canvas.extend({
	init: function(src)	{
		this._super();
		this.src = src;
		this.img = new Image(src);
		this.baseDotTL = new Image('images/delete-small.png');
		this.resizeDotBR = new Image('images/sq.png');
		this.dummyDotTR = new Image('images/sq.png');
		this.dummyDotBL = new Image('images/sq.png');
		this.rotateIcon = new RotatableImage('images/sq.png');
		this.textArea = new TextArea('');
		this.text = new Label('');

		this.addObject(this.resizeDotBR);
		this.addObject(this.baseDotTL);
		this.addObject(this.dummyDotTR);
		this.addObject(this.dummyDotBL);
		this.addObject(this.rotateIcon);
		this.addObject(this.textArea);
		this.addObject(this.text);
		this.addObject(this.img);
		this.type = "imagebox";
		this.className = "ImageBox";
		
		app.getObjectManager().registerMainObjects(this);
	},
	
	getTextArea: function()	{
		return this.textArea;
	},
	
	getZIndex: function()	{
		if(this.zIndex == null){
			this.zIndex = this.access().css("z-index");
		}
		if(this.zIndex == null){
			this.zIndex = 1000;
		}
		return this.zIndex;
	},
	
	setZIndex: function(index)	{
		this.zIndex = index;
		this.setStyle("z-index",this.zIndex);
		this.update();
	},
	
	showTextArea: function()	{
		this.text.hide();
		this.textArea.show();
		this.textArea.focus();
	},
	
	showPlainText: function()	{
		this.textArea.hide();
		this.text.show();
		this.text.center();
	},
	
	afterCreate: function()	{
		this._super();
		
		this.resizeDotBR.implement(new ResizableBR());
		this.rotateIcon.implement(new Rotatable());
		this.dummyDotTR.implement(new ResizableTR());
		this.dummyDotBL.implement(new ResizableBL());
		this.baseDotTL.implement(new DeleteImageBox());
		
		this.img.addClass('img-item');
		this.img.setStyle('height', '50px');
		
		var d = new DraggableWrapper();
		d.wrap(this);
		d.wrap(this.resizeDotBR);
		d.wrap(this.rotateIcon);
		d.wrap(this.dummyDotTR);
		d.wrap(this.dummyDotBL);
		
		this.baseDotTL.addClass('sq');
		this.resizeDotBR.addClass('sq');
		this.dummyDotTR.addClass('sq');
		this.dummyDotBL.addClass('sq');
		this.rotateIcon.addClass('sq');
		
		this.updateImages();

		this.implement(new DragSelectImageBox());
		this.implement(new ClickImageBox());
		this.implement(new ClickImageCreateText());
		this.implement(new CreateImageBoxContextMenu());
		this.showPlainText();
		this.baseDotTL.setStyle('position','absolute');
	},
	
	updateText: function(txt,font)	{
		this.text.setText(txt,font);
		this.showPlainText();
	},
	
	updateImages: function()	{
		var dim = this.img.getDimension();
		this.resizeTo(dim.width, dim.height);
		// move base dot & resize dot to top-left and bottom-right respectively
		// and relatively
		var x0 = -11;
		var y0 = -11;
		var x1 = dim.width-5;
		var y1 = dim.height-5;
		
		this.baseDotTL.moveTo(y0, x0);		
		this.resizeDotBR.moveTo(y1-5, x1-5);
		this.dummyDotTR.moveTo(y0, x1);
		this.dummyDotBL.moveTo(y1, x0);
		this.rotateIcon.moveTo(y1/2-10, x1+10);
	},
	
	select: function()	{
		this.baseDotTL.show();
		this.resizeDotBR.show();
		this.dummyDotTR.show();
		this.dummyDotBL.show();
		this.rotateIcon.show();
	},
	
	deselect: function()	{
		this.baseDotTL.hide();
		this.resizeDotBR.hide();
		this.dummyDotTR.hide();
		this.dummyDotBL.hide();
		this.rotateIcon.hide();
	},
	
	deserializeText: function(txt,fontData)	{
		this.getTextArea().txt = txt;
		var f = new Font();
		f.setFont(fontData.fontFamily, fontData.fontSize, fontData.bold, fontData.italic, fontData.color);
		this.getTextArea().setFont(f);
	},
	
	serialize: function()	{
		var obj = this._super();
		obj.params = {};
		obj.params.src = this.src;
		obj.params.style = this.serializeStyle();
		obj.params.txt = this.getTextArea().getText();
		obj.params.font = this.getTextArea().getFont();
		return obj;
	},
	
	afterLoad: function()	{
		this._super();
		this.img.resizeTo(this.getDimension().width, this.getDimension().height);
		this.updateImages();
		this.getTextArea().access().val(this.getTextArea().txt);
		this.updateText(this.getTextArea().getText(), this.getTextArea().getFont());
	}
});

Deserializer = Class.extend({
	deserialize: function(serialized)	{
		if (serialized.className == "ImageBox")	{
			var imageBox = new ImageBox(serialized.params.src);
			imageBox.deserializeStyle(serialized.params.style);
			imageBox.deserializeText(serialized.params.txt,serialized.params.font);
			return imageBox;
		}
	}
});

Button = DisplayObject.extend({
	init: function(txt)	{
		this._super();
		this.txt = txt;
		this.id = generateId('button');
		this.type = "Button";
		this.className = "Button";
	},
	
	toHtml: function()	{
		return "<button id='"+this.id+"' class='"+this.getType()+"'>"+this.txt+"</button>";
	}
});

ToggleButton = DisplayObject.extend({
	init: function(txt,state)	{
		this._super();
		this.txt = txt;
		this.id = generateId('togglebutton');
		this.type = "togglebutton";
		this.className = "ToggleButton";
		this.state = state;
		this.implement(new ClickToggleButton());
	},
	
	afterCreate: function(){
		this._super();
		if(this.state){
			this.addClass("toggledown");
		}
	},
	
	toHtml: function()	{
		return "<a id='"+this.id+"' class='"+this.getType()+"'>"+this.txt+"</a>";
	}
});

/*
* IconSet class. An icon set is a group of icons, grouped by a label which can perform accordion behaviour.
*/

IconSet = Canvas.extend({
	init: function(lbl)	{
		this._super();
		this.lblText = lbl;
		this.container = new Canvas();
		this.header = new Canvas();
		this.label =  new Label('');
		this.header.addObject(this.label);
		this.addObject(this.header);
		this.addObject(this.container);
	},
	
	afterCreate: function()	{
		this.label.addClass('ij-iconsetlbl');
		this.label.setText(this.lblText);
		this.setStyle('position','relative');
		this.header.setStyle('width',(this.access().width()+10)+"px");
		this.header.addClass('ij-headericonset');
		this.container.addClass('ij-containericonset');
		this.header.implement(new ClickHeaderIconSet());
	},
	
	addIcon: function(img){
		img = new ImageIconWrapper().wrap(img);
		img = new ClickableImageWrapper().wrap(img);
		this.container.addObject(img);
	}
});

ToolBox = Canvas.extend({
	init: function()	{
		this._super();
		// FIXME: Store this list in another location?
		this.type = "toolbox";
		this.id = "tool";
		this.addClass("tool");
		this.iconSets = new Array();
	},

	addIcon: function(img)	{
		img = new ImageIconWrapper().wrap(img);
		img = new ClickableImageWrapper().wrap(img);
		this.addObject(img);
	},
	
	addIconSet: function(lbl)	{
		iconset = new IconSet(lbl);
		this.iconSets.push(iconset);
		this.addObject(iconset);
	},
	
	addIconToSet: function(id,img)	{
		this.iconSets[id].addIcon(img);
	}
});

/**
 * IMPLEMENTOR & HANDLERS
 */

ClickImageBox = InterfaceImplementor.extend({
	implement: function(obj)	{
		this.bind(obj, new ClickImageBoxHandler());
	}
});

ClickImageBoxHandler = Handler.extend({
	getEventName: function()	{
		return "click";
	},
	
	onEvent: function(e, obj)	{
		app.select(obj);
		e.stopPropagation();
	}
});

ResizableTR = InterfaceImplementor.extend({
	implement: function(obj)	{
		this.bind(obj, new ResizableTRDragHandler());
		this.bind(obj, new ResizableDragStopHandler());
		this.bind(obj, new MouseOverSqHandler("tr"));
		this.bind(obj, new MouseOutSqHandler("tr"));
	}
});

ResizableTRDragHandler = Handler.extend({
	getEventName: function()	{
		return "drag";
	},
	
	onEvent: function(e, obj)	{		
		var parent = obj.getParent();
		var left = obj.getPosition().left;
		var min = 50;
		var w = left - parent.baseDotTL.getPosition().left - 7;
		var h = parent.access().height();
		if (w < min)	{
			obj.setStyle('left', min);
			obj.access().draggable('disable');
			w = min;
		}
		parent.img.resizeTo(w, h);
		parent.updateImages();
	}
});

ResizableBL = InterfaceImplementor.extend({
	implement: function(obj)	{
		this.bind(obj, new ResizableBLDragHandler());
		this.bind(obj, new ResizableDragStopHandler());
		this.bind(obj, new MouseOverSqHandler("bl"));
		this.bind(obj, new MouseOutSqHandler("bl"));		
	}
});

ResizableBLDragHandler = Handler.extend({
	getEventName: function()	{
		return "drag";
	},
	
	onEvent: function(e, obj)	{		
		var parent = obj.getParent();
		var top = obj.getPosition().top;
		var min = 50;
		var w = parent.access().width();
		var h = top - parent.baseDotTL.getPosition().top - 7;
		if (h < min)	{
			obj.setStyle('left', min);
			obj.access().draggable('disable');
			h = min;
		}
		parent.img.resizeTo(w, h);
		parent.updateImages();
	}
});


ResizableBR = InterfaceImplementor.extend({
	implement: function(obj)	{
		this.bind(obj, new ResizableBRDragHandler());
		this.bind(obj, new ResizableDragStopHandler());
		this.bind(obj, new MouseOverSqHandler("br"));
		this.bind(obj, new MouseOutSqHandler("br"));		
	}
});

ResizableDragStopHandler = Handler.extend({
	getEventName: function()	{
		return "dragstop";
	},

	onEvent: function(e, obj)	{
		obj.access().draggable('enable');
		obj.getParent().updateImages();
	}
});

ResizableBRDragHandler = Handler.extend({
	getEventName: function()	{
		return "drag";
	},

	onEvent: function(e, obj)	{
		var parent = obj.getParent();
		var left = obj.getPosition().left;
		var top = obj.getPosition().top;
		
		var min = 50;
		var h = top - parent.baseDotTL.getPosition().top - 7;
		var w = left - parent.baseDotTL.getPosition().left - 7;
		if (h < min)	{
			obj.setStyle('top', min);
			obj.access().draggable('disable');
			h = min;
		}
		
		if (w < min)	{
			obj.setStyle('left', min);
			obj.access().draggable('disable');
			w = min;
		}
		
		parent.img.resizeTo(w, h);
		parent.updateImages();
	}
});

MouseOverSqHandler = Handler.extend({
	init: function(type)	{
		this.type = type;
	},

	getEventName: function()	{
		return "mouseover";
	},
	
	onEvent: function(e, obj)	{
		var styleName = "sq"+this.type;
		obj.access().addClass("sqhover");
		obj.access().addClass(styleName);
	}
});

MouseOutSqHandler = Handler.extend({
	init: function(type)	{
		this.type = type;
	},

	getEventName: function()	{
		return "mouseout";
	},
	
	onEvent: function(e, obj)	{
		styleName = "sq"+this.type;
		obj.access().removeClass("sqhover");
		obj.access().removeClass(styleName);
	}
});

DragSelectImageBox = InterfaceImplementor.extend({
	implement: function(obj)	{
		this.bind(obj, new DragSelectImageBoxHandler());
// this.bind(obj, new DragStopImageBoxHandler());
	}
});

DragStopImageBoxHandler = Handler.extend({
	getEventName: function()	{
		return "dragstop";
	},
	
	onEvent: function(e, obj)	{
		app.select(obj);
	}
});

DragSelectImageBoxHandler = Handler.extend({
	getEventName: function()	{
		return "drag";
	},
	
	onEvent: function(e, obj)	{
		app.select(obj);
// obj.deselect();
	}
});

ClickIcon = InterfaceImplementor.extend({
	implement: function(obj)	{
		this.bind(obj, new ClickIconHandler());
	}
});

ClickIconHandler = Handler.extend({
	getEventName: function()	{
		return "click";
	},
	
	onEvent: function(e, obj)	{
		var main = app.getMainArea();
		var toolBox = app.getToolBox();
		var item = new ImageBox(obj.getSrc());
		var i = 0;
		main.addObject(item);
		
		item.addClass('item');
		item.moveTo(toolBox.getPosition().top, 600);
		app.select(item);
		
		items = main.getObjects();
		i = items.length;
		items[i] = i;
		item.setZIndex(i);
		item.setAttribute('state','silent');
	}
});

ClickImageCreateText = InterfaceImplementor.extend({
	implement: function(obj)	{
		this.bind(obj, new ClickImageCreateTextHandler());
	}
});

ClickImageCreateTextHandler = Handler.extend({
	getEventName: function()	{
		return "dblclick";
	},
	
	onEvent: function(e, obj)	{
		obj.showTextArea();
	}
});

ClickTextAreaStopEvent = InterfaceImplementor.extend({
	implement: function(obj)	{
		this.bind(obj, new ClickTextAreaStopEventHandler());
	}
});

ClickTextAreaStopEventHandler = Handler.extend({
	getEventName: function()	{
		return "click";
	},
	
	onEvent: function(e, obj)	{
		e.stopPropagation();
	}
});

BlurTextAreaUpdate = InterfaceImplementor.extend({
	implement: function(obj)	{
		this.bind(obj, new BlurTextAreaUpdateHandler());
	}
});
	
BlurTextAreaUpdateHandler = Handler.extend({
	getEventName: function()	{
		return "blur";
	},
	
	onEvent: function(e, obj)	{
		obj.updateText();
	}
});

ClickCanvasDeselect = InterfaceImplementor.extend({
	implement: function(obj)	{
		this.bind(obj, new ClickCanvasDeselectHandler());
	}
});
	
ClickCanvasDeselectHandler = Handler.extend({
	getEventName: function()	{
		return "click";
	},
	
	onEvent: function(e, obj)	{
		app.deselect();
	}
});

Rotatable = InterfaceImplementor.extend({
	implement: function(obj)	{
		this.bind(obj, new RotateMouseMove());
		this.bind(obj, new RotateStop());
	}
});

RotateStop = Handler.extend({
	getEventName: function()	{
		return "dragstop";
	},

	onEvent: function(e, obj)	{
		obj.getParent().updateImages();
	}
});

RotateMouseMove = Handler.extend({
	getEventName: function()	{
		return "drag";
	},

	onEvent: function(e, obj)	{
		obj.rotate(e);
	}
});

ClickAlert = InterfaceImplementor.extend({
	implement: function(obj)	{
		this.bind(obj, new ClickAlertHandler());
	}
});

ClickAlertHandler = Handler.extend({
	getEventName: function()	{
		return "click";
	},

	onEvent: function(e, obj)	{
		alert('hello');
	}
});

DeleteImageBox = InterfaceImplementor.extend({
	implement: function(obj)	{
		this.bind(obj, new DeleteImageBoxHandler());
		this.bind(obj, new MouseOverSqHandler("tl"));
		this.bind(obj, new MouseOutSqHandler("tl"));	
	}
});

DeleteImageBoxHandler = Handler.extend({
	getEventName: function()	{
		return "click";
	},
	
	onEvent: function(e, obj)	{
		obj.parent.dispose();
	}
});

ClickExportJPG = InterfaceImplementor.extend({
	implement: function(obj)	{
		this.bind(obj, new ClickExportJPGHandler());
	}
});

ClickExportJPGHandler = Handler.extend({
	getEventName: function()	{
		return "click";
	},
	
	onEvent: function(e, obj)	{
		toimg();
	}
});

ClickHeaderIconSet = InterfaceImplementor.extend({
	implement: function(obj)	{
		this.bind(obj, new ClickHeaderIconSetHandler());
	}
});

ClickHeaderIconSetHandler = Handler.extend({
	getEventName: function()	{
		return "click";
	},
	
	onEvent: function (e, obj)	{
		obj.parent.container.access().toggle();
	}
});

CreateImageBoxContextMenu = InterfaceImplementor.extend({
	implement: function(obj)	{
		this.bind(obj, new CreateImageBoxContextMenuHandler());
	}
});

CreateImageBoxContextMenuHandler = InterfaceImplementor.extend({
	getEventName: function()	{
		return "contextmenu";
	},
	
	onEvent: function (e, obj)	{
		e.preventDefault();
		if(app.getObjectManager().context != null){
			app.getObjectManager().context.dispose();
		}
		var contextMenu = new ContextMenu();
		var moveToBack = new ContextMenuItem('Move to back',obj);
		var moveBackward = new ContextMenuItem('Move backward',obj);
		var moveToFront = new ContextMenuItem('Move to front',obj);
		var moveForward = new ContextMenuItem('Move forward',obj);
		var properties = new ContextMenuItem('Properties',obj);
		var zIndex = new ContextMenuItem('Z-index',obj);
		var main = app.getMainArea();
		var _top = e.pageY;
		var _left = e.pageX;		
				
		properties.implement(new EventPropertiesContextMenu());
		zIndex.implement(new EventZIndexContextMenu());
		moveToBack.implement(new EventMoveToBackContextMenu());
		moveBackward.implement(new EventMoveBackwardContextMenu());
		moveToFront.implement(new EventMoveToFrontContextMenu());		
		moveForward.implement(new EventMoveForwardContextMenu());

		contextMenu.addItem(moveToBack);
		contextMenu.addItem(moveToFront);
		contextMenu.addItem(moveBackward);
		contextMenu.addItem(moveForward);
		contextMenu.addItem(zIndex);
		contextMenu.addItem(properties);
		
		main.addObject(contextMenu);
		contextMenu.setStyle('top',_top);
		contextMenu.setStyle('left',_left);
		objMgr = app.getObjectManager().registerContext(contextMenu);
	}
});

EventMoveToBackContextMenu = InterfaceImplementor.extend({
	implement: function(obj)	{
		this.bind(obj, new ClickMoveToBackContextMenuHandler());
		this.bind(obj, new MouseOverContextMenuItemHandler());
		this.bind(obj, new MouseOutContextMenuItemHandler());
	}
});

ClickMoveToBackContextMenuHandler = Handler.extend({
	getEventName: function(){
		return "click";
	},
	
	onEvent: function(e,obj){
		var objManager = app.getObjectManager();
		var obj = obj.getOriginObject();
		var thisZIndex = obj.getZIndex();
		var indexArr = new Array();
		var mainObjects = objManager.getMainObjects();
		for(var i=0;i<mainObjects.length;i++){
			indexArr.push(mainObjects[i].getZIndex());
		}
		var minIndex = Array.min(indexArr);
		if(minIndex == thisZIndex){
			return;
		}else{
			for(var i=0;i<mainObjects.length;i++){
				if(mainObjects[i].getZIndex() < thisZIndex){
					mainObjects[i].setZIndex(Array.nextBigger(indexArr,mainObjects[i].getZIndex()));
				}
			}
			obj.setZIndex(minIndex);
		}
		/*
		* update display
		*/
		for(var i=0;i<mainObjects.length;i++){
			mainObjects[i].update();
		}
	}
});

EventMoveToFrontContextMenu = InterfaceImplementor.extend({
	implement: function(obj)	{
		this.bind(obj, new ClickMoveToFrontContextMenuHandler());
		this.bind(obj, new MouseOverContextMenuItemHandler());
		this.bind(obj, new MouseOutContextMenuItemHandler());
	}
});

ClickMoveToFrontContextMenuHandler = Handler.extend({
	getEventName: function(){
		return "click";
	},
	
	onEvent: function(e,obj){
		var objManager = app.getObjectManager();
		var obj = obj.getOriginObject();
		var thisZIndex = obj.getZIndex();
		var indexArr = new Array();
		var mainObjects = objManager.getMainObjects();
		for(var i=0;i<mainObjects.length;i++){
			indexArr.push(mainObjects[i].getZIndex());
		}
		var maxIndex = Array.max(indexArr);
		if(maxIndex == thisZIndex){
			return;
		}else{
			for(var i=0;i<mainObjects.length;i++){
				if(mainObjects[i].getZIndex() > thisZIndex){
					mainObjects[i].setZIndex(Array.nextLess(indexArr,mainObjects[i].getZIndex()));
				}
			}
			obj.setZIndex(maxIndex);
		}
		/*
		* update display
		*/
		for(var i=0;i<mainObjects.length;i++){
			mainObjects[i].update();
		}	}
});

EventMoveBackwardContextMenu = InterfaceImplementor.extend({
	implement: function(obj)	{
		this.bind(obj, new ClickMoveBackwardContextMenuHandler());
		this.bind(obj, new MouseOverContextMenuItemHandler());
		this.bind(obj, new MouseOutContextMenuItemHandler());
	}
});

ClickMoveBackwardContextMenuHandler = Handler.extend({
	getEventName: function(){
		return "click";
	},
	
	onEvent: function(e,obj){
		var objManager = app.getObjectManager();
		var obj = obj.getOriginObject();
		var thisZIndex = obj.getZIndex();
		var indexArr = new Array();
		var mainObjects = objManager.getMainObjects();
		for(var i=0;i<mainObjects.length;i++){
			indexArr.push(mainObjects[i].getZIndex());
		}
		var minIndex = Array.min(indexArr);
		var id = -1;
		if(minIndex == thisZIndex){
			return;
		}else{
			minIndex = -1;
			for(var i=0;i<mainObjects.length;i++){
				if(mainObjects[i].getZIndex() < thisZIndex && mainObjects[i].getZIndex() > minIndex){
					minIndex = mainObjects[i].getZIndex();
					id = i;
				}
			}
			mainObjects[id].setZIndex(thisZIndex);
			obj.setZIndex(minIndex);
		}
		app.select(obj);
		for(var i=0;i<mainObjects.length;i++){
			mainObjects[i].update();
		}
	}
});

EventMoveForwardContextMenu = InterfaceImplementor.extend({
	implement: function(obj)	{
		this.bind(obj, new ClickMoveForwardContextMenuHandler());
		this.bind(obj, new MouseOverContextMenuItemHandler());
		this.bind(obj, new MouseOutContextMenuItemHandler());
	}
});

ClickMoveForwardContextMenuHandler = Handler.extend({
	getEventName: function(){
		return "click";
	},
	
	onEvent: function(e,obj){
		var objManager = app.getObjectManager();
		var obj = obj.getOriginObject();
		var thisZIndex = obj.getZIndex();
		var indexArr = new Array();
		var mainObjects = objManager.getMainObjects();
		for(var i=0;i<mainObjects.length;i++){
			indexArr.push(mainObjects[i].getZIndex());
		}
		var maxIndex = Array.max(indexArr);
		var id = -1;
		if(maxIndex == thisZIndex){
			return;
		}else{
			maxIndex = 1000;
			for(var i=0;i<mainObjects.length;i++){
				if(mainObjects[i].getZIndex() > thisZIndex && mainObjects[i].getZIndex() < maxIndex){
					maxIndex = mainObjects[i].getZIndex();
					id = i;
				}
			}
			mainObjects[id].setZIndex(thisZIndex);
			obj.setZIndex(maxIndex);
		}
		app.select(obj);
		for(var i=0;i<mainObjects.length;i++){
			mainObjects[i].update();
		}
	}
});

EventZIndexContextMenu = InterfaceImplementor.extend({
	implement: function(obj)	{
		//this.bind(obj, new ClickPropertiesContextMenuHandler());
		this.bind(obj, new MouseOverContextMenuItemHandler());
		this.bind(obj, new MouseOutContextMenuItemHandler());
	}
});

EventPropertiesContextMenu = InterfaceImplementor.extend({
	implement: function(obj)	{
		this.bind(obj, new ClickPropertiesContextMenuHandler());
		this.bind(obj, new MouseOverContextMenuItemHandler());
		this.bind(obj, new MouseOutContextMenuItemHandler());
	}
});

MouseOverContextMenuItemHandler = Handler.extend({
	getEventName: function()	{
		return "mouseover";
	},
	
	onEvent: function (e,obj)	{
		obj.setStyle('background-color','#888');
		obj.setStyle('color','#fff');
	}
});

MouseOutContextMenuItemHandler = Handler.extend({
	getEventName: function()	{
		return "mouseout";
	},
	
	onEvent: function (e,obj)	{
		obj.setStyle('background-color','#fff');
		obj.setStyle('color','#000');
	}
});

ClickPropertiesContextMenuHandler = Handler.extend({
	getEventName: function()	{
		return "click";
	},
	
	onEvent: function (e,obj)	{
		var str = "<div style='padding-left:50px; text-align:left'>";
		var controls = new Array();
		var btnOK = new Button("OK");
		var btnApply = new Button("Apply");
		var font = obj.getOriginObject().getTextArea().getFont();
		controls.push(btnApply);
		controls.push(btnOK);
		str += "Top:"+obj.getOriginObject().getPosition().top+"px ; Left:"+obj.getOriginObject().getPosition().left+"px<br/>";
		str += "Width:"+obj.getOriginObject().access().width()+"px ; Height:"+obj.getOriginObject().access().height()+"px<br/>";
		str += "Font-size: <input type='text' id='properties-font-size' value='"+font.getFontSize()+"' /><br/>";
		str += "Bold, Italic, etc<br/>";
		str += "Font-family: <input type='text' id='properties-font-family' value='"+font.getFontFamily()+"' /><br/>";
		str += "Color: <input type='text' id='properties-font-color' value='"+font.getColor()+"' /><br/>";
		str += "</div>";
		dialogId = dialog("Properties",str,controls);
		btnApply.implement(new ClickPropertiesButtonApply(obj.getOriginObject()));
		btnOK.implement(new ClickPropertiesButtonOK(dialogId,obj.getOriginObject()));
	}
});

ClickPropertiesButtonApply = InterfaceImplementor.extend({
	init: function(obj)	{
		this._super();
		this.obj = obj;
	},
	
	implement: function(obj)	{
		this.bind(obj, new ClickPropertiesButtonApplyHandler(this.obj));
	}
});

ClickPropertiesButtonApplyHandler = Handler.extend({
	init: function(obj){
		this.obj = obj;
	},
	
	getEventName: function(){
		return "click";
	},
	
	onEvent: function(e,o)	{
		var font = this.obj.getTextArea().getFont();
		font.setFontSize($("#properties-font-size").val());
		font.setFontFamily($("#properties-font-family").val());
		font.setColor($("#properties-font-color").val());
		this.obj.getTextArea().setFont(font);
		this.obj.getTextArea().updateText();
	}
});

ClickPropertiesButtonOK = InterfaceImplementor.extend({
	init: function(dialogId,obj)	{
		this._super();
		this.obj = obj;
		this.id = dialogId;
	},
	
	implement: function(obj)	{
		this.bind(obj, new ClickPropertiesButtonOKHandler(this.id,this.obj));
	}
});

ClickPropertiesButtonOKHandler = Handler.extend({
	init: function(id,obj){
		this.obj = obj;
		this.id = id;
	},
	
	getEventName: function(){
		return "click";
	},
	
	onEvent: function(e,o)	{
		var font = this.obj.getTextArea().getFont();
		font.setFontSize($("#properties-font-size").val());
		font.setFontFamily($("#properties-font-family").val());
		font.setColor($("#properties-font-color").val());
		this.obj.getTextArea().setFont(font);
		this.obj.getTextArea().updateText();
		$("#dialog_div_"+this.id).remove();
	}
});

SaveDiagram = InterfaceImplementor.extend({
	implement: function(obj)	{
		this.bind(obj, new ClickSaveDiagramHandler());
	}
});

ClickSaveDiagramHandler = Handler.extend({
	getEventName: function()	{
		return "click";
	},
	
	onEvent: function (e,obj)	{
		var objs = app.getObjectManager().getMainObjects();			
		var str = "";
		var o;
		var controls = new Array();
		var btnSave = new Button("Save");
		var btnCancel = new Button("Cancel");
		var dialogId;
		var dname;
		var objsToSave = new Array();
		for(var i=0;i<objs.length;i++){
			o = objs[i];
			var objToSave = objs[i].serialize();
			objsToSave.push(objToSave);
		}
		str += "Diagram Name: <input type='text' id='diagramname' value='default' />";
		controls.push(btnSave);
		controls.push(btnCancel);
		dialogId = dialog("Object detail",str,controls);
		dname = $("#diagramname");
		btnCancel.implement(new CloseDialog(dialogId));
		btnSave.implement(new SaveFile(dialogId,dname,objsToSave));
	}
});

SaveFile = InterfaceImplementor.extend({
	init: function(dialogId,dname,objsToSave){
		this._super();
		this.id = dialogId;
		this.dname = dname;
		this.objsToSave = objsToSave;
	},
	
	implement: function(obj){
		this.bind(obj, new ClickSaveFileHandler(this.id,this.dname,this.objsToSave));
	}
});

ClickSaveFileHandler = Handler.extend({
	init: function(id,dname,objsToSave){
		this.id = id;
		this.dname = dname;
		this.objsToSave = objsToSave;
	},
	
	getEventName: function(){
		return "click";
	},

	onEvent: function(e,obj){
		var name = this.dname.val();
		var json = {};
		var url = 'services/save.php';
		json.name = name;
		json.diagram = $.toJSON(this.objsToSave);
		$.ajax({
			cache: false,
			type:'POST',
			url: url,
			data: json,
			beforeSend: function(){
				alertMsg("alert","<img src='images/wait.gif'/>");
			},
			complete: function (data){
				alertMsg("alert",name +" is saved");
			}
		});
		
		$("#dialog_div_"+this.id).remove();
	}
	
});

LoadDiagram = InterfaceImplementor.extend({
	implement: function(obj)	{
		this.bind(obj, new ClickLoadDiagramHandler());
	}
});

ClickLoadDiagramHandler = Handler.extend({
	getEventName: function()	{
		return "click";
	},
	
	onEvent: function (e,obj)	{
		var str = "";
		var btnLoad = new Button("Load");
		var controls = new Array();
		var dname = "";
		var url = "services/listDiagrams.php";
		$.ajax({
			cache: false,
			type:'GET',
			url: url,
			beforeSend: function(){
				$("#dialogload-dlist").html("<img src='images/wait.gif'/>");
			},
			complete: function (data){
				var diagrams = $.parseJSON(data.responseText);
				var str = "";
				for(var i=0;i<diagrams.length;i++)	{
					var diagram = diagrams[i];
					str += diagram.name+",";
				}
				$("#dialogload-dlist").html(str);
			}
		});		
		str = "<div id='dialogload-dlist'></div>Diagram Name: <input id='diagramname' name='diagramname' type='text'/>";
		controls.push(btnLoad);
		dialogId = dialog("Choose file",str,controls);
		dname = $("#diagramname"); 
		btnLoad.implement(new ExtractDiagram(dialogId,dname));
	}
});

ExtractDiagram = InterfaceImplementor.extend({
	init: function(id,diagram)	{
		this._super();
		this.id = id;
		this.diagram = diagram;
	},
	
	implement: function(obj)	{
		this.bind(obj, new ExtractDiagramHandler(this.id, this.diagram));
	}
});

ExtractDiagramHandler = Handler.extend({
	init: function(id,diagram){
		this._super();
		this.id = id;
		this.diagram = diagram;
	},
	
	getEventName: function(){
		return "click";
	},
	
	onEvent: function(e,obj) {
		var diagramname = this.diagram.val(); 
		$("#dialog_div_"+this.id).remove();
		var objs = app.getObjectManager().getMainObjects();
		var url = 'services/load.php';
		url += '?name='+diagramname;
		while(objs.length > 0){
			objs[0].dispose();			
		}
		$.ajax({
			cache: false,
			type:'GET',
			url: url,
			beforeSend: function(){
				alertMsg("alert","<img src='images/wait.gif'/>");
			},
			complete: function (data){
				var strToLoad = data.responseText;
				var objsToLoad = $.parseJSON(strToLoad);
				var deserializer = new Deserializer();
				for(var i=0;i<objsToLoad.length;i++)	{
					var obj = objsToLoad[i];
					var deserializedObj = deserializer.deserialize(obj);
					app.getMainArea().addObject(deserializedObj);
					deserializedObj.afterLoad();
				}				
				alertMsg("alert","Completed !");
			}
		});
	}
});

CloseDialog = InterfaceImplementor.extend({
	init: function(id)	{
		this._super();
		this.id = id;
	},
	
	implement: function(obj)	{
		this.bind(obj, new CloseDialogHandler(this.id));
	}
});

CloseDialogHandler = Handler.extend({
	init: function(id)	{
		this._super();
		this.id = id;
	},

	getEventName: function ()	{
		return "click";
	},
	
	onEvent: function (e,obj)	{
		$("#dialog_div_"+this.id).remove();
	}
});

ClickToggleButton = InterfaceImplementor.extend({
	implement: function(obj)	{
		this.bind(obj, new ClickToggleButtonHandler());
	}
});

ClickToggleButtonHandler = Handler.extend({
	getEventName: function()	{
		return "click";
	},
	
	onEvent: function(e,obj)	{
		obj.access().toggleClass("toggledown");
		if(obj.access().hasClass("toggledown")){
			obj.state = true;
		}else{
			obj.state = false;
		}
	}
});

TestToggle = InterfaceImplementor.extend({
	implement: function(obj)	{
		this.bind(obj, new ClickTestToggleHandler());
	}
});

ClickTestToggleHandler = Handler.extend({
	getEventName: function()	{
		return "click";
	},
	
	onEvent: function(e,obj)	{
		dialog("alert","fine: "+obj.state,null);
	}
});
EventBinder = Class.extend	({
	fireEvent: function(jObject, event)	{
		jObject.trigger(event);
	},

	bindEvent: function(jObject, handlers)	{
		jObject.access().bind(handlers.getEventName(), function(e)	{
			handlers.onEvent(e, jObject);
		});
	}
});
/**
 * Observer interface. 
 * Used for formalizing the observer design pattern,
 * especially in an event-based application
 * Provide the following methods:
 *  - notify(eventName, eventData): called when an arbitrary event is triggered
 *  - registerObserver(): register the current object to be an observer
 *  - unregisterObserver(): unregister the current object, and it's no longer an observer
 *  @augments InterfaceImplementor
 *  @author griever
 */
ObserverInterface = InterfaceImplementor.extend({
	
	implement: function(obj)	{
		obj.prototype.notify = obj.prototype.notify || function(eventName, eventData)	{
			var methodName = "on"+eventName;
			if (typeof this[methodName] != 'undefined')	{
				var method = this[methodName];
				method.call(this, eventData);
				return true;
			}
			return false;
		};
		
		obj.prototype.registerObserver = obj.prototype.registerObserver || function()	{
			var subject = SingletonFactory.getInstance(Subject);
			subject.attachObserver(this);
		};
		
		obj.prototype.unregisterObserver = obj.prototype.unregisterObserver || function()	{
			var subject = SingletonFactory.getInstance(Subject);
			subject.detachObserver(this);
		};
	}
});

/**
 * Event Subject (mediator or notifier)
 * @augments Class
 * @author griever
 */
Subject = Class.extend({
	
	/**
	 * Initialize fields
	 * @constructor
	 */
	init: function()	{
		this.observers = Array();
	},
	
	/**
	 * Attach an observer
	 * @function
	 * @param {observer} the observer
	 */
	attachObserver: function(observer)	{
		this.observers.push(observer);
	},
	
	/**
	 * Detach an observer
	 * @function
	 * @param {observer} the observer
	 */
	detachObserver: function(observer)	{
		if (observer == undefined)
			return;
		var index = this.observers.indexOf(observer);
		if (index > 0)	{
			this.observers.splice(index, 1);
		}
	},
	
	/**
	 * Notify an event to all observers
	 * @function
	 * @param {eventName} the name of the event which should contains characters only
	 * @param {eventData} the data associated with the event
	 */
	notifyEvent: function(eventName, eventData)	{
		var count = 0;
		for(var i=0;i<this.observers.length;i++)	{
			var result = this.observers[i].notify(eventName, eventData);
//			if (result == true && eventName=='LoginSuccess')	{
//				console.log('observer '+this.observers[i].getName());
//			}
			if (result == true)	{
				count++;
			}
		}
	}
});
/**
 * PluginManager. Manages all registered plugins
 * @augments Class
 * @author griever
 */
PluginManager = Class.extend({
	
	/**
	 * Initialize fields
	 * @constructor
	 */
	init: function()	{
		if(PluginManager.singleton == undefined){
			throw "Singleton class, can not be directly created !";
			return undefined;
		}
		var subject = SingletonFactory.getInstance(Subject);
		subject.attachObserver(this);
		this.plugins = Array();
	},
	
	/**
	 * Add plugin to the manager
	 * @function
	 * @param {plugin} the plugin to be added
	 * @param {delay} whether the plugin should be loaded after added
	 */
	addPlugin: function(plugin, delay)	{
		var pluginMeta = {};
		if (delay != true)
			plugin.onLoad();
		this.plugins.push(plugin);
	},
	
	/**
	 * Remove plugin at the specified index
	 * @function
	 * @param {index} the index of the plugin to be removed
	 */
	removePlugin: function(index)	{
		var plugin = this.plugins[index];
		if (plugin != undefined)	{
			plugin.onUnload();
			this.plugins.splice(index, 1);
		}
	},
	
	/**
	 * Get all plugins
	 * @function
	 * @returns {Array} the current plugins
	 */
	getPlugins: function()	{
		return this.plugins;
	},
	
	/**
	 * Remove every plugins managed by this manager
	 * @function
	 */
	removeAllPlugins: function()	{
		for(var i=0;i<this.plugins.length;i++)	{
			var plugin = this.plugins[i];
			if (plugin.isLoaded())	{
				plugin.onUnload();
			}
		}
		this.plugins = Array();
	},
	
	/**
	 * Event hook. Triggered by the Subject and in turn triggers all plugins that it manages
	 * @function
	 * @param {eventName} the event name
	 * @param {eventData} the event data
	 */
	notify: function(eventName, eventData)	{
		for(var i=0;i<this.plugins.length;i++)	{
			var plugin = this.plugins[i];
			if (plugin.isLoaded())	{
				var methodName = "on"+eventName;
				if (typeof plugin[methodName] != 'undefined')	{
					var method = plugin[methodName];
					method.call(plugin, eventData);
				}
			}
		}
	}
}).implement(ObserverInterface);

/**
 * The plugin interface.
 * Provide the following methods:
 *  - isLoaded(): check if the plugin is loaded
 *  - getName(): get the plugin's name
 *  - onLoad(): called when the plugin is loaded
 *  - onBegin(): called when the plugin begins its routine
 *  - onEnd(): called when the plugin ends its routine
 *  - onUnload(): called when the plugin is unloaded from memory
 * @augments InterfaceImplementor
 * @author griever
 */
PluginInterface = InterfaceImplementor.extend({
	implement: function(obj)	{

		obj.prototype.isLoaded = obj.prototype.isLoaded || function()	{
			if (this.loaded == undefined)
				this.loaded = false;
			return this.loaded;
		};
		
		obj.prototype.getName = obj.prototype.getName || function()	{
			return this.name;
		};
		
		obj.prototype.onLoad = obj.prototype.onLoad || function()	{
			this.loaded = true;
			this.onBegin();
		};
		
		obj.prototype.onBegin = obj.prototype.onBegin || function() {};
		
		obj.prototype.onEnd = obj.prototype.onEnd || function() {};
		
		obj.prototype.onUnload = obj.prototype.onUnload || function()	{
			this.loaded = false;
			this.onEnd();
		};
		
		//super interfaces
		new ObserverInterface().implement(obj);
	}
});

/**
 * Interval timer interface. Used for circular portlets or plugins
 * Provide the following methods:
 *  - startInterval(interval, callback): start the interval timer
 *  - stopInterval(): stop the interval timer
 *  @augments InterfaceImplementor
 *  @author griever
 */
IntervalTimerInterface = InterfaceImplementor.extend({
	implement: function(obj)	{
		obj.prototype.startInterval = obj.prototype.startInterval || function(interval, callback)	{
			//stop previous interval timer if any
			if (this.intervalSetup == true)	{
				this.stopInterval();
			}
			this.intervalSetup = true;
			var _this = this;
			this.currentIntervalID = setInterval(function() {callback.call(_this);}, interval);
		};
		
		obj.prototype.stopInterval = obj.prototype.stopInterval || function()	{
			if (this.currentIntervalID != undefined)
				clearInterval(this.currentIntervalID);
			else	{
				//console.warn('bug! currentIntervalID not defined');
			}
		};
	}
});
/**
 * Page is a class for attaching portlets to appropriate position
 * a Page manages the display 
 * FIXME: not sure about provide supporting for template in each page ! 
 * currently unsupport
 * @augments Class
 * @author griever
 */

Page = Class.extend({
	
	/**
	 * Initialize fields
	 * @constructor
	 */
	init: function(){
		if(Page.singleton == undefined){
			throw "Page is Singleton !";
			return undefined;
		}
		this.portletContainer = SingletonFactory.getInstance(PortletContainer);
		this.pluginManager = SingletonFactory.getInstance(PluginManager);
		this.pagename = "";
		this.subject = SingletonFactory.getInstance(Subject);
	},
	
	/**
	 * Attach portlets to the page
	 * @function
	 */
	attachPortlets: function(){
		/*
		 * check for consistency with layout in here
		 * + portlet existence
		 * + portlet position
		 * + portlet active (?)
		 */
		for( var item in this.layout ){
			item = this.layout[item];
			if(item.active == undefined){
				item.active = true;
			}
			if (item.params == undefined)	{
				item.params = Array();
			}
			var existed = false;
			for( var i=0; i<this.portletContainer.portlets.length; i++ )	{
				var portletMeta = this.portletContainer.portlets[i];
				if( item.portlet === portletMeta.portlet.getName() ){
					existed = true;
					portletMeta.portlet.setInitParameters(item.params);
					if( item.position === portletMeta.position ){
						if( item.active !== portletMeta.active ){
							portletMeta.active = item.active;
							// FIXME: portletMeta.portlet.active ~> something like this must be implemented
						}
					}else{
						portletMeta.position = item.position;
						this.portletContainer.movePortlet(portletMeta,item.position);
					}
					if ( item.active == true)	{
						//portlet need reload?
						portletMeta.portlet.onReloadPage();
					}
					break;
				}
			}
			if(!existed){
				if (window[item.portlet] == undefined)	{
					
				} else {
					var portlet = new window[item.portlet]();
					portlet.setInitParameters(item.params);
					this.portletContainer.addPortlet(portlet,item);
				}
			}
		}
		var portletsToRemoved = Array();
		for( var i=0; i<this.portletContainer.portlets.length; i++ )	{
			var portletMeta = this.portletContainer.portlets[i];
			var keep = false;
			for(var item in this.layout){
				item = this.layout[item];
				if( item.portlet === portletMeta.portlet.getName() ){
					if (item.active == false)	{
						this.portletContainer.deactivatePortlet(portletMeta);
					}
					keep = true;
					break;
				}
			}
			if(!keep){
				portletsToRemoved.push(portletMeta);
			}
		}
		for(var i=0;i<portletsToRemoved.length;i++)	{
			var plt = portletsToRemoved[i];
			var indexOf = this.portletContainer.portlets.indexOf(plt);
			this.portletContainer.removePortlet(indexOf);
		}
	},
	
	/**
	 * Private function
	 * Parse the layout
	 * @function
	 */
	generateData: function(pagename){
		var data = {};
		var tmp = {};

		if (pagename == undefined)	{
			throw {"Exception": "NotFound", "Message": "Page name is undefined"};
			return undefined;
		}
		var app = SingletonFactory.getInstance(Application);
		var jsonObj = app.getResourceManager().requestForResource("portlets",pagename);
		if (jsonObj == undefined)	{
			//console.error(pagename+' not exist!');
			throw {"Exception": "NotFound", "Message": 'Page name "'+pagename+'" not found!'};
			return undefined;
		}
		var jsonText = jsonObj.html();
		tmp = eval("("+jsonText+")");
		data.parent = tmp.parent;
		data.plugins = tmp.plugins;
		data.layout = tmp.portlets;
		var i,j;
		var toAddPlugins = new Array();
		var toAddPortlets = new Array();
		while(data.parent != undefined){
			jsonObj = app.getResourceManager().requestForResource("portlets",data.parent);
			if (jsonObj == undefined)	{
				//console.error(data.parent+' not exist!');
				throw {"Exception": "NotFound", "Message": '(Parent)Page name "'+data.parent+'" not found!'};
				return undefined;
			}
			jsonText = jsonObj.html();
			toAddPlugins = new Array();
			toAddPlugins = new Array();
			tmp = eval("("+jsonText+")");
			for( i=0; i<tmp.plugins.length; i++ )	{
				var existed = false;
				for( j=0; j<data.plugins.length; j++ )	{
					if(tmp.plugins[i].plugin == data.plugins[j].plugin){
						existed = true;
						break;
					}
				}
				if(!existed){
					toAddPlugins.push(tmp.plugins[i]);
				}
			}
			for( i=0; i<tmp.portlets.length; i++ )	{
				var existed = false;
				for( j=0; j<data.layout.length; j++ )	{
					if(tmp.portlets[i].portlet == data.layout[j].portlet){
						existed = true;
						break;
					}
				}
				if(!existed){
					toAddPortlets.push(tmp.portlets[i]);
				}
			}
			for( i=0;i<toAddPlugins.length;i++ ){
				data.plugins.push(toAddPlugins[i]);
			}
			for( i=0;i<toAddPortlets.length;i++ ){
				data.layout.push(toAddPortlets[i]);
			}
			data.parent = tmp.parent;
		}
		/*
		if(tmp.position != undefined){
			data.template = app.getResourceManager().requestForResource("page",pagename).html();
			data.position = tmp.position;
		}
		*/
		return data;
	},
	
	/**
	 * Get the current request
	 * @function
	 * @returns {Request} the current request
	 */
	getRequest: function(){
		return this.request;
	},
	
	/**
	 * Change the current request
	 * This method <b>should not</b> be called by developers
	 * @function
	 * @param {Request} the new request
	 */
	setRequest: function(request){
		this.request = request;
	},
	
	/**
	 * Attach plugins to the page
	 * @function
	 */
	attachPlugins: function(){
		var oldPlugins = this.pluginManager.getPlugins();
		for(var i in oldPlugins)	{
			var oldPlg = oldPlugins[i];
//			//console.log('old plugin: '+oldPlg.getName());
			oldPlg.keep = false;
		}
		
		for (var j in this.plugins)	{
			var newPlg = this.plugins[j];
			//check if the plugin exists
			for(var i=0; i<oldPlugins.length; i++)	{
				var existed = false;
				var oldPlg = oldPlugins[i];
//				//console.log('check plugin '+newPlg.plugin+' against '+oldPlg.getName());
				if (oldPlg.getName() == newPlg.plugin)	{
					//console.log('plugin '+newPlg.plugin+' existed!');
					oldPlg.keep = true;
					existed = true;
					break;
				}
			}
			if (!existed)	{
				//console.log("load plugin: "+newPlg.plugin);
				if(window[newPlg.plugin] == undefined){
					//console.warn('Plugin '+newPlg.plugin+' is undefined!');
				} else {
					var plugin = new window[newPlg.plugin];
					plugin.keep = true;
					this.pluginManager.addPlugin(plugin, eval(newPlg.delay));
				}
			}
		}
		
		//find plugins that need to be removed
		var pluginsToRemoved = Array();
		for(var i in oldPlugins){
			var oldPlg = oldPlugins[i];
			if (oldPlg.keep != true)	{
				//console.log('plugin removed: '+oldPlg.getName());
				pluginsToRemoved.push(oldPlg);
			}
		}
		
		//removed unused plugins
		for(var i=0;i<pluginsToRemoved.length;i++)	{
			var plg = pluginsToRemoved[i];
			var indexOf = this.pluginManager.getPlugins().indexOf(plg);
			this.pluginManager.removePlugin(indexOf);
		}
		
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent('ReloadPlugin');
//		//console.log('newplugin', this.pluginManager.getPlugins());
	},
/*
	attachTemplate: function(){
		if(this.position != undefined){
				//console.log("attachTemplate");
				this.temp = new Array();
				for(var i in $("#"+this.position).children()){
					if(!isNaN(i)){
						var obj = $($("#"+this.position).children()[i]);
						obj.detach();
						this.temp.push(obj);
					}
				}
				//console.log("position:"+this.position);
				$("#"+this.position).html(this.template);
		}
	},
	
	wrapUpDisplay: function(){
		if(this.position != undefined){
			var tmp = new Array();
			for(var i in $("#"+this.position).children()){
				if(!isNaN(i)){
					var obj = $($("#"+this.position).children()[i]);
					obj.detach();
					tmp.push(obj);
				}
			}
			
			$("#"+this.position).html(tmp);
		}
	},
*/
	
	/**
	 * Called when the page begins its routine
	 * Parse the layout and attach plugins
	 * @param {pagename} the page name
	 * @function
	 */
	onBegin: function(pagename)	{
		var data = this.generateData(pagename);
		if (data == undefined)
			return;
		this.pagename = pagename;
		this.layout = data.layout;
		this.plugins = data.plugins;
		this.attachPlugins();
		this.subject.notifyEvent("PageBegan");
		/*
		this.template = data.template;
		this.position = data.position;
		*/
	},
	
	/**
	 * Run the page, attach portlets
	 */
	run: function()	{
		/*
		this.attachTemplate();
		*/
		this.attachPortlets();		
		this.subject.notifyEvent("AllPorletAdded");
		this.portletContainer.loadPortlets();
		this.subject.notifyEvent("AllPorletLoaded");
		/*
		this.wrapUpDisplay();
		*/
	},
	
	onEnd: function()	{
		
	},
	
	dispose: function()	{
		
	}
});
PortletCanvas = Canvas.extend({
	init: function()	{
		this._super();
		this.addClass('portlet');
		this.addClass('portlet-canvas');
	}
});

/**
 * An interface for all portlets
 * Exposed method:
 * 	- void onBegin()
 *  - void run()
 *  - void onEnd()
 *  - String getName()
 *  - void setPortletPlaceholder(PortletPlaceholder)
 *  - PortletPlaceholder getPortletPlaceholder()
 *  - getPage(): get the current page
 *  - getRequest(): get the current request
 *  - requestForResource(): get the resource in the prepared portlet-data
 *  - requestForEffectiveResource(): get the resource in the portlet's DOM
 *  - getLocalizedText(): get the localized text by ID
 *  - getLocalizedMessage(): get the message by ID
 *  @augments InterfaceImplementor
 *  @author griever
 */
PortletInterface = InterfaceImplementor.extend({
	implement: function(obj)	{
		obj.prototype.getName = obj.prototype.getName || function()	{
			return this.name;
		};
		obj.prototype.onBegin = obj.prototype.onBegin || function(){};
		obj.prototype.run = obj.prototype.run || function(){};
		obj.prototype.onEnd = obj.prototype.onEnd || function(){};
		obj.prototype.setPortletPlaceholder = obj.prototype.setPortletPlaceholder || function(plhd)	{
			this.placeholder = plhd;
		};
		
		obj.prototype.getPage = obj.prototype.getPage || function()	{
			return SingletonFactory.getInstance(Page);
		};
		
		obj.prototype.getInitParameters = obj.prototype.getInitParameters || function()	{
			if (this.initParams == undefined)
				this.initParams = Array();
			return this.initParams;
		};
		
		obj.prototype.setInitParameters = obj.prototype.setInitParameters || function(params)	{
			this.initParams = params;
		};
		
		obj.prototype.getRequest = obj.prototype.getRequest || function()	{
			return this.getPage().getRequest();
		};
		
		obj.prototype.requestForMatchingEffectiveResource = obj.prototype.requestForMatchingEffectiveResource || function(resourceName, condition)	{
			var app = SingletonFactory.getInstance(Application);
			var rm = app.getResourceManager();
			return rm.requestForCustomResource("#effective-area #"+this.name+"-"+resourceName+" "+condition);
		};
		
		obj.prototype.requestForResource = obj.prototype.requestForResource || function(resourceName)	{
			var app = SingletonFactory.getInstance(Application);
			var rm = app.getResourceManager();
			return rm.requestForCustomResource("#"+this.name+"-RootData #"+this.name+"-"+resourceName);
		};
		
		obj.prototype.requestForEffectiveResource = obj.prototype.requestForEffectiveResource || function(resourceName)	{
			var app = SingletonFactory.getInstance(Application);
			var rm = app.getResourceManager();
			return rm.requestForCustomResource("#effective-area #"+this.name+"-"+resourceName);
		};
		
		obj.prototype.onReloadPage = obj.prototype.onReloadPage || function()	{};
		
		obj.prototype.getResourceID = obj.prototype.getResourceID || function(resourceName)	{
			return this.name+"-"+resourceName;
		};
		
		obj.prototype.getLocalizedText = obj.prototype.getLocalizedText || function(resourceName)	{
			var app = SingletonFactory.getInstance(Application);
			var rm = app.getResourceManager();
			var res = rm.requestForResource(this.name, "Text"+resourceName);
			if (res == undefined)
				return undefined;
			return res.html();
		};
		
		obj.prototype.getLocalizedMessage = obj.prototype.getLocalizedMessage || function(resourceName)	{
			var app = SingletonFactory.getInstance(Application);
			var rm = app.getResourceManager();
			var res = rm.requestForResource(this.name, "Message"+resourceName);
			if (res == undefined)
				return undefined;
			var unresolved = res.html();
			
			var resolved = unresolved;
			//resolved string pattern
			for(var i=1;i<arguments.length;i++)	{
				resolved = resolved.replace("%"+i, arguments[i]);
			}
			return resolved;
		};
		
		obj.prototype.getPortletPlaceholder = obj.prototype.getPortletPlaceholder || function()	{
			return this.placeholder;
		};
	}
});

/**
 * An interface for all ajax-based portlets or plugins
 * Provide the following methods:
 *  - onAjax(controller, action, params, type, callback)
 */
AjaxInterface = InterfaceImplementor.extend({
	implement: function(obj)	{
		var interfacePrivate = function(ret, success, fail)	{
			ret = $.parseJSON(ret);
			var result = ret.result;
			if (result != 'error' && result != 'internal-error')	{
				if (success != undefined)
					success.call(undefined, ret.result);
			}
			else	{
				if (fail != undefined)
					fail.call(undefined, ret.message);
			}
		};
		obj.prototype.onAjax = obj.prototype.onAjax || function(controller, action, params, type, callbacks, cache, cacheTime)	{
			if (type == undefined)
				type = 'GET';
			var success = callbacks.onSuccess;
			var fail = callbacks.onFailure;
			var accessDenied = callbacks.onAccessDenied;
			
			var memcacheKey = 'ajax.'+controller+'.'+action;
			for(var k in params)	{
				var v = params[k];
				memcacheKey += '.'+k+'.'+v;
			}

			//try to get from mem cached
			if (type == 'GET' && cache == true)	{
				var memcache = SingletonFactory.getInstance(Memcached);
				var value = memcache.retrieve(memcacheKey);
				if (value != undefined)	{
					var now = new Date();
					var cacheTimestamp = value.timestamp;
					if ((now.getTime() - cacheTimestamp) < cacheTime)	{
						interfacePrivate(value.ret, success, fail);
						return;
					} else {
						memcache.clear(memcacheKey);
					}
				}
			}
			var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
			var url = root+controller+'/'+action;
			var subject = SingletonFactory.getInstance(Subject);
			$.ajax({
				url: url,
				type: type,
				data: params,
				success: function(ret)	{
					if (type == 'GET' && cache == true)	{
						//cache the result
						var memcache = SingletonFactory.getInstance(Memcached);
						var now = new Date();
						memcache.store(memcacheKey, {'ret': ret, 'timestamp': now.getTime()});
					}
					interfacePrivate(ret, success, fail);
				},
				error: function(ret, textStatus)	{
//					console.log('error while performing AJAX request: '+url+'. Status: '+textStatus);
				},
				statusCode: {
					403: function()	{
						//console.log('access denied at '+url);
						if (accessDenied != undefined)
							accessDenied.call(undefined);
					}
				}
			});
		};
	}
});

/**
 * An interface for all portlets which need rendering
 * Exposed method:
 * 	- Object model
 * 	- String viewId
 *  - void render()
 */
RenderInterface = InterfaceImplementor.extend({
	implement: function(obj)	{
		obj.prototype.render = obj.prototype.render || function(){
			this.viewId = this.viewId || this.getName()+"View";
			this.model = this.model || {};
//			if(this.viewId == undefined || this.model == undefined){
//				throw "No viewId or model for rendering";
//			}
			return tmpl(this.viewId, this.model);
		};
		
		obj.prototype.renderView = obj.prototype.renderView || function(view, model)	{
			return tmpl(this.name+"-"+view, model);
		};
	}
});

/**
 * A placeholder to store a single portlet
 * It acts as a bridge between Portlet and PortletCanvas
 * @augments Class
 * @author griever
 */
PortletPlaceholder = Class.extend({
	init: function(canvas)	{
		this.canvas = canvas;
	},
	
	/**
	 * Add an object to canvas
	 * @function
	 * @param {object} the object to add
	 */
	addToCanvas: function(object)	{
		//console.log('add '+object.toHtml()+' into '+this.canvas.id);
		this.canvas.addObject(object);
	},
	
	/**
	 * Clear everything and repaint the canvas
	 * @param {html} the HTML data to be painted
	 * @function
	 */
	paintCanvas: function(html)	{
		this.canvas.access().html(html);
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent('HtmlUpdated');
	},
	
	/**
	 * Append to the canvas
	 * @param {html} the HTML data to be appended
	 * @function
	 */
	drawToCanvas: function(html)	{
		this.canvas.access().append(html);
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent('HtmlUpdated');
	},
	
	/**
	 * Access the underlying canvas
	 * @returns {PortletCanvas} the canvas
	 */
	getCanvas: function()	{
		return this.canvas;
	}
});

/**
 * A container which 'runs' multiple portlets
 */
PortletContainer = Class.extend({
	init: function()	{
		if(PortletContainer.singleton == undefined){
			throw "Singleton class";
			return undefined;
		}
		this.portlets = Array();
	},
	
	/**
	 * Add a portlet to this container and initialize it
	 * @function
	 * @param {portlet} the portlet to be added
	 * @param {position} the position of the portlet
	 * @param {active} whether the portlet should be loaded
	 */
	addPortlet: function(portlet, item)	{
//		console.log('adding portlet: '+portlet.getName(), 'color: red');
		var portletMeta = {};
		for(var i in item)	{
			portletMeta[i] = item[i];
		}
		portletMeta.portlet = portlet;
		if (portletMeta.order == undefined)
			portletMeta.order = '';
		portletMeta.loaded = false;
		this.portlets.push(portletMeta);
		try 
		{
			portlet.onBegin();
		} 
		catch (err)	{
//			console.error(err);
//			alert(err);
		}
	},
	
	/**
	 * Move the portlet to another position
	 * @function
	 * @param {portlet} the portlet to be moved
	 * @param {newPosition} the new position
	 */
	movePortlet: function(portletMeta, newPosition)	{
		var portletPosition = new PrebuiltCanvas(newPosition);
		var portletCanvas = new PrebuiltCanvas(portlet.getPortletPlaceholder().getCanvas().id);
		this.attachPortletHtml(portletPosition, portletCanvas, portletMeta);
	},
	
	/**
	 * Load all active portlets, execute them synchronously
	 * @function
	 */
	loadPortlets: function()	{
		for(var i=0;i<this.portlets.length;i++)	{
			var portletMeta = this.portlets[i];
			if (portletMeta.active == true && !portletMeta.loaded)	{
				this.activatePortlet(portletMeta);
				portletMeta.loaded = true;
			}
		}
	},
	
	/**
	 * Get all portlets
	 * @function
	 * @returns {Array} All loaded portlets
	 */
	getPortlets: function()	{
		return this.portlets;
	},
	
	/**
	 * Get portlet meta using the portlet's name
	 * @function
	 * @param {name} the portlet's name
	 */
	getPortletMetaByName: function(name)	{
		var i;
		for( i=0; i<this.portlets.length; i++ ){
			if(this.portlets[i].portlet.getName() == name){
				return this.portlets[i];
			}
		}
	},
	
	/**
	 * Remove portlet at the specified position
	 * @function
	 * @param {position} the position of the portlet to be removed
	 */
	removePortlet: function(position)	{
		var portletMeta = this.portlets[position];
		if (portletMeta != undefined)	{
			this.portlets.splice(position,1);
			portletMeta.portlet.onEnd();
			if (portletMeta.portlet.getPortletPlaceholder())	{
				//console.log("dispose canvas of portlet: "+portletMeta.portlet.getName());
				portletMeta.portlet.getPortletPlaceholder().getCanvas().dispose();
			}
		}
	},
	
	attachPortletHtml: function(portletPosition, portletCanvas, portletMeta)	{
		var jPortletCanvas = portletPosition.access();
		var canvases = jPortletCanvas.find('.portlet.portlet-canvas');

		var found = false;
		for(var i=0;i<canvases.length;i++)	{
			var canvasI = canvases[i];
			if ($(canvasI).attr('order') > portletMeta.order)	{
				portletPosition.addObjectBeforePosition(portletCanvas, canvasI);
				found = true;
				break;
			}
		}
		
		if (found == false)	{
			portletPosition.addObject(portletCanvas);
		}
		portletCanvas.access().attr('order', portletMeta.order);
	},
	
	/**
	 * Activate a portlet
	 * @function
	 * @param {portletMeta} the metadata of the portlet to be activated
	 */
	activatePortlet: function(portletMeta)	{
		var portlet = portletMeta.portlet;
		if (portletMeta.loaded)	{
			return;
		}
		var portletPosition = new PrebuiltCanvas(portletMeta.position);
		var portletCanvas = new PortletCanvas();
		this.attachPortletHtml(portletPosition, portletCanvas, portletMeta);
		var portletPlaceholder = new PortletPlaceholder(portletCanvas);
		portlet.setPortletPlaceholder(portletPlaceholder);
		portletMeta.loaded = true;
		try 
		{
			portlet.run();
		} 
		catch (err)	{
//			console.error(err);
//			alert(err);
		}
	},
	
	/**
	 * Deactivate a portlet
	 * @function
	 * @param {portletMeta} the metadata of the portlet to be deactivated
	 */
	deactivatePortlet: function(portletMeta)	{
		var portlet = portletMeta.portlet;
		if (!portletMeta.loaded)	{
			return;
		}
		portletMeta.loaded = false;
		if (portlet.getPortletPlaceholder())	{
			portlet.getPortletPlaceholder().paintCanvas('');
		}
	}
});
DefaultErrorHandler = Class.extend({
	handle: function(err, event) {
		if (typeof err == 'object') {
			if (err.Exception == 'RequestInterrupted') {
				return;
			}
			alert("["+err.Exception+"Exception] "+err.Message);
			return;
		}
		alert("Error caught: "+err);
	}
});

/**
 * Represents a request
 */
Request = Class.extend({
	init: function(name, type, params, hideParams) {
		if (name != undefined)
			name = name.trim();
		this.name = name;
		this.type = type;
		if (params == undefined) {
			params = Array();
		}
		if (hideParams == undefined) {
			hideParams = Array();
		}
		this.params = params;
		this.hiddenParams = hideParams;
		this.setParams(params);
		this.demanded = true;
	},
	/**
	 * Check if the request is demanded by the application itself
	 * @function
	 * @returns {bool} true or false
	 */
	isDemanded: function() {
		return this.demanded;
	},
	
	/**
	 * Change the demanding flag of the current request
	 * Demanded request will be automatically routed
	 * @function
	 * @param {b} the demanding flag
	 */
	demand: function(b) {
		this.demanded = b;
	},
	setParam: function(key, value) {
		this.params[key] = value;
	},
	setParams: function(params) {
		this.params = params;
	},
	getParam: function(key, defaultValue) {
		if (this.params[key] == undefined) {
			return defaultValue;
		}
		return this.params[key];
	},
	getParams: function() {
		return this.params;
	},
	addHash: function(strToAdd) {
		window.location.hash = strToAdd;
	},
	setName: function(name) {
		this.name = name;
	},
	getName: function() {
		return this.name;
	},
	getType: function() {
		return this.type;
	}
});

Request.setProactive = function(b, url) {
	if (url == undefined)
		url = window.location.hash;
	//console.log('set proactive to '+b+' for url: '+url);
	//	//console.warn('called by '+Request.setProactive.caller);
	if (Request.proactive == undefined)
		Request.proactive = {};
	Request.proactive[url] = b;
};
Request.getProactive = function(url) {
	if (url == undefined)
		url = window.location.hash;
	if (Request.proactive == undefined)
		Request.proactive = {};
	return Request.proactive[url];
};
RequestHandler = Class.extend({
	
	/**
	 * Init fields
	 * @constructor
	 */
	init: function() {
		this.currentPage = undefined;
		this.requestInterrupted = false;
		this.autoRouteDefault = true;
		this.systemProperties = SingletonFactory.getInstance(Application).getSystemProperties();
		this.errorHandler = new DefaultErrorHandler();
	},
	
	/**
	 * Change the error handler
	 */
	setErrorHandler: function(errorHandler) {
		this.errorHandler = errorHandler;
	},
	
	/**
	 * Route (if needed) and handle a request
	 * @function
	 * @param {request} the request to be handled
	 */
	handleRequest: function(request) {
		//console.log('current page is '+this.currentPage);
		if (this.currentPage != undefined) {
			//console.log("Request Interrupted");
			this.requestInterrupted = true;
		} else {
			this.requestInterrupted = false;
		}
		this.routeRequest(request);
		this._handleRequest(request);
	},
	
	_handleRequest: function(request) {
		var name = request.getName();
		var page = SingletonFactory.getInstance(Page);
		this.currentPage = page;
		page.setRequest(request);
		//console.log('current page begin: '+request.getName());
		try 
		{
			page.onBegin(name);
		} 
		catch (err) {
			//console.error(err);
			/*
			* display a message similar to 'this applet failed to load. click here to reload it'
			*/
			this.errorHandler.handle(err, 'onBegin');
		}

		//console.log('current page running: '+request.getName());

		try 
		{
			page.run();
		} 
		catch (err) {
			//console.log(err);
			/*
 			* display a message box notify the error
 			*/
			this.errorHandler.handle(err, 'run');
		}

		try 
		{
			page.onEnd();
		} 
		catch (err) {
			//console.error(err);
			this.errorHandler.handle(err, 'onEnd');
		}

		//console.log('current page finished: '+request.getName());
		this.currentPage = undefined;

		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent("HtmlRendered");
		//		//console.log(currentPage);
		if (this.requestInterrupted == true) {
			throw {"Exception":"RequestInterrupted"};
		}
	},
	
	/**
	 * Define setter and getter for the window location hash
	 */
	prepareForRequest: function() {
		if(!("hash" in window.location)) {
			window.location.__defineGetter__("hash", function() {
				if(location.href.indexOf("#") == -1)
					return "";
				return location.href.substring(location.href.indexOf("#"));
			});
			window.location.__defineSetter__("hash", function(v) {
				if(location.href.indexOf("#") == -1)
					location.href += v;
				location.href = location.substring(0,location.href.indexOf("#")) + v;
			});
		}
	},
	
	/**
	 * Create a request based on the current URL
	 * @function
	 */
	assembleRequest: function() {
		var defaultPage = SingletonFactory.getInstance(Application).getSystemProperties().get('page.default', 'Home');
		if(window.location.hash == "") {
			var request = new Request(defaultPage, null, null, {'page': ''});
			var subject = SingletonFactory.getInstance(Subject);
			return request;
		} else {
			//console.log("hey!");
			var hash = window.location.hash;
			hash = hash.substring(1,hash.length);
			var tmp = hash.split("/");
			var params = new Array();
			var pagename = "";
			var i = 0;

			while(i<tmp.length) {
				if(tmp[i] != "") {
					params[tmp[i]] = tmp[i+1];
					if(tmp[i] == "page") {
						pagename = params[tmp[i]];
					}
					i = i + 2;
				} else {
					i = i + 1;
				}
			}

			var request = new Request(pagename, null, params);
			request.demand(false);
			return request;
		}
	},
	
	/**
	 * Modify the URL (i.e the window location) based on the request
	 * @function
	 * @param {request} the request to be routed
	 */
	routeRequest: function(request) {
		//if this request neither proactive nor demanded, then there's no point routing it
		if (Request.getProactive() == false && request.isDemanded() == false)
			return;
		var oldHash = window.location.hash;
		var str = "";
		if ( ( request.getName() == undefined || request.getName() == "" ) && this.autoRouteDefault ) {
			var pagename = this.systemProperties.get('page.default');
			//console.warn('page is undefined! Using default homepage ['+pagename+']');
			if (pagename == undefined) {
				//console.error('Default page is undefined! I give up for now!');
				throw {"Exception": "NotFound", "Message": "Both default page and parameter page is undefined"};
				return undefined;
			}
			request.setName(pagename);
			request.hiddenParams.page = '';
		}
		request.getParams()['page'] = request.getName();
		for(var key in request.getParams()) {
			if (request.hiddenParams.hasOwnProperty(key)) {
				continue;
			}
			if (typeof request.getParams()[key] !== 'string')
				return;
			value = request.params[key];
			if (value != undefined)
				str += key+"/"+value+"/";
			else
				str += key+"/";
		}
		str = str.substring(0,str.length-1);
		if(!("hash" in window.location)) {
			window.location.__defineGetter__("hash", function() {
				if(location.href.indexOf("#") == -1)
					return "";
				return location.href.substring(location.href.indexOf("#"));
			});
			window.location.__defineSetter__("hash", function(v) {
				if(location.href.indexOf("#") == -1)
					location.href += v;
				location.href = location.substring(0,location.href.indexOf("#")) + v;
			});
		}
		//mark the current request as Proactive, so it won't trigger another history event
		Request.setProactive(true, '#'+str);
		window.location.hash = str;
	}
});

/**
 * The bootstrap class.
 * The application's flow is defined here
 * Implement ObserverInterface
 * @augments Class
 */
Bootstrap = Class.extend({
	/**
	 * Called when the application start running
	 * Subclass can override this method to change the default flow
	 * @function
	 */
	run: function()	{
		this.registerObserver();
		this.setupRequestHandler();
	},

	/**
	 * Event-hooked function.
	 * @function
	 */
	onRequestRoute: function(eventData)	{
		this.requestHandler.handleRequest(eventData);
	},
	
	/**
	 * Event-hooked function.
	 * @function
	 */
	onNeedAssembleRequest: function(eventData)	{
		this.executeRequest();
	},

	/**
	 * Initialize the request handler
	 * @function
	 */
	setupRequestHandler: function()	{
		this.requestHandler = new RequestHandler();
		this.requestHandler.setErrorHandler(new BKErrorHandler());
		this.executeRequest();
	},
	
	/**
	 * Execute the current request
	 * @function
	 */
	executeRequest: function()	{
		this.requestHandler.prepareForRequest();
		var request = this.requestHandler.assembleRequest();
		if (request != undefined)	{
			var subject = SingletonFactory.getInstance(Subject);
			subject.notifyEvent('RequestRoute', request);
		}
	}
}).implement(ObserverInterface);
/**
 * 
 */

utils_items = {};

/**
 * Generate an unique ID
 * 
 * @param type
 *            String
 * @returns
 */
function generateId(type)	{
	if (!isPropertySet(utils_items, type))	{
		setProperty(utils_items, type, 0);
	}
	setProperty(utils_items, type, getProperty(utils_items, type)+1);
	return type+"-"+getProperty(utils_items, type);
}

function formatDate(dateValue, dateStr){
	if(!dateStr){
		dateStr = "dddd, mmmm dS, yyyy, h:MM:ss TT";
	}
	
	//dateValue = dateValue.replace(/[a-zA-Z]/g," ");
	//dateValue = dateValue.replace("  "," ");
	try {
		var date = new Date(dateValue);
		if(date == undefined || date == null || isNaN(date)){
			return dateValue;
		}
		return $.format.date(date, "HH:mm dd/MM/yyyy")
	} catch (e) {
		// TODO: handle exception
		return dateValue;
	}
	
}

function generateEvent(eventName, eventData){
    var subject = SingletonFactory.getInstance(Subject);
    subject.notifyEvent(eventName, eventData);
}

function setProperty(obj, prop, val)	{
	obj.prop = val;
}

function getProperty(obj, prop)	{
	return obj.prop;
}

function isPropertySet(obj, prop)	{
	if (typeof obj.prop != 'undefined')	{
		return true;
	}
	return false;
}


Array.max = function( array ){
    return Math.max.apply( Math, array );
};
Array.min = function( array ){
    return Math.min.apply( Math, array );
};

Array.nextBigger = function( array,val ){
	var result = Number.MAX_VALUE;
	for(var i=0; i < array.length; i++){
		if(array[i] > val && array[i] < result){
			result = array[i];
		}
	}
	return result;
};

Array.nextLess = function( array,val ){
	var result = Number.MIN_VALUE;
	for(var i=0; i < array.length; i++){
		if(array[i] < val && array[i] > result){
			result = array[i];
		}
	}
	return result;
};

function dialog ( title,msg,controls ){
	var id = Math.floor(Math.random()*101);
	var dialog_div = document.createElement("div");
	var dialog_header = document.createElement("div");
	var dialog_content = document.createElement("div");
	var dialog_control = document.createElement("div");
	var dialog_lbl = document.createElement("label");
	var btnClose = new Image("images/close.png");
	dialog_content.appendChild(dialog_lbl);
	dialog_div.appendChild(dialog_header);
	dialog_div.appendChild(dialog_content);
	dialog_div.appendChild(dialog_control);
	dialog_div.setAttribute('id','dialog_div_'+id);
	dialog_header.setAttribute('id','dialog_header_'+id);
	dialog_content.setAttribute('id','dialog_content_'+id);
	dialog_control.setAttribute('id','dialog_control_'+id);
	dialog_lbl.setAttribute('id','dialog_lbl_'+id);
	document.getElementsByTagName("body")[0].appendChild(dialog_div);
	$('#dialog_lbl_'+id).html(msg);
	$('#dialog_header_'+id).html(title+btnClose.toHtml());
	if(controls != null){
		var str = "";
		for(var i=0;i<controls.length;i++){
			str += controls[i].toHtml();
		}
		$('#dialog_control_'+id).html(str);
	}
	$('#dialog_div_'+id).addClass('alert_div');
	$('#dialog_header_'+id).addClass('alert_header');
	$('#dialog_content_'+id).addClass('alert_content');
	$('#dialog_control_'+id).addClass('alert_content');
	btnClose.setStyle("float","right");
	btnClose.setStyle("margin-right","5px");
	var _width = $(window).width();
	var _height = $(window).height();	
	var _top = (_height - $("#dialog_div_"+id).height())/2;
	var _left = (_width - $("#dialog_div_"+id).width())/2;
	$("#dialog_div_"+id).css('top',_top);
	$("#dialog_div_"+id).css('left',_left);	
	$("#dialog_div_"+id).draggable();
	$("#dialog_div_"+id).css('zIndex','1000');
	btnClose.implement(new CloseDialog(id));
	return id;
}

function alertMsg(title,msg) {
	var alert_div = document.createElement("div");
	var alert_header = document.createElement("div");
	var alert_content = document.createElement("div");
	var alert_control = document.createElement("div");
	var alert_btn = document.createElement("button");
	var alert_lbl = document.createElement("label");
	alert_content.appendChild(alert_lbl);
	alert_control.appendChild(alert_btn);	
	alert_div.appendChild(alert_header);
	alert_div.appendChild(alert_content);
	alert_div.appendChild(alert_control);
	alert_div.setAttribute('id','alert_div');
	alert_header.setAttribute('id','alert_header');
	alert_content.setAttribute('id','alert_content');
	alert_control.setAttribute('id','alert_control');
	alert_btn.setAttribute('id','alert_btn');
	alert_lbl.setAttribute('id','alert_lbl');
	document.getElementsByTagName("body")[0].appendChild(alert_div);
	$('#alert_lbl').html(msg);
	$('#alert_header').html(title);
	$('#alert_btn').html('OK');
	$('#alert_div').addClass('alert_div');
	$('#alert_header').addClass('alert_header');
	$('#alert_content').addClass('alert_content');
	$('#alert_control').addClass('alert_content');
	var _width = $(window).width();
	var _height = $(window).height();	
	var _top = (_height - $("#alert_div").height())/2;
	var _left = (_width - $("#alert_div").width())/2;
	$("#alert_div").css('top',_top);
	$("#alert_div").css('left',_left);	
	$("#alert_div").draggable();
	$("#alert_div").css('zIndex','1000');
	$("#alert_btn").addClass('ij-button');
	$("#alert_btn").bind('click',function(){
		$("#alert_div").remove();
	});
}
/**
 * A wrapper of the system properties.
 * Used for accessing the memcached namespace
 * @augments Class
 * @author griever
 */
Memcached = Class.extend({
	
	/**
	 * Initialize fields
	 * @constructor
	 */
	init: function()	{
		this.properties = SingletonFactory.getInstance(Application).getSystemProperties();
	},
	
	/**
	 * Private function.
	 * Get the actual entry name for the the specified key
	 */
	getEntryName: function(key)	{
		return 'memcached.'+key;
	},
	
	/**
	 * Store a value in the specified key
	 * @function
	 * @param {key} the key
	 * @param {value} the new value
	 */
	store: function(key, value)	{
		var entry = this.getEntryName(key);
		this.properties.set(entry, value);
	},
	
	/**
	 * Retrieve the value of the specified key
	 * @function
	 * @param {key} the key
	 * @returns {mixed} the value of the key
	 */
	retrieve: function(key)	{
		var entry = this.getEntryName(key);
		return this.properties.get(entry);
	},
	
	/**
	 * Clear the content of the specified key
	 * @function
	 * @param {key} the key
	 */
	clear: function(key)	{
		var entry = this.getEntryName(key);
		this.properties.set(entry, undefined);
	}
});
BKBootstrap = Bootstrap.extend({
	
}).implement(ObserverInterface);

BKErrorHandler = DefaultErrorHandler.extend({
	handle: function(err, event)	{
		if (typeof err == 'object')	{
			if (err.Exception == 'NotFound')	{
				var request = new Request("ErrorPage", null, {'code': 404});
				var subject = SingletonFactory.getInstance(Subject);
				subject.notifyEvent("RequestRoute", request);
			} else if (err.Exception == 'RequestInterrupted')	{
				return;
			}
		}
	}
});
SearchMorePlugin = Class.extend({
	init: function()	{
		this.name = "SearchMorePlugin";
	},
	
	onHtmlUpdated: function()	{
		$('.extension-point[extensionName="PostResultList"]').each(function(index, value) {
			if ($(value).find('[flag="SearchMore"]').length > 0)	{
				return;
			}
			$(value).append('<div><center><button class="search-more" onclick="generateEvent('+"'GetMoreResultRows'"+')">Xem các câu hỏi tiếp</button></center></div><div flag="SearchMore"></div>');
		});
	}
}).implement(PluginInterface);
CleanStylePlugin = Class.extend({
	init: function()	{
		this.name = "CleanStylePlugin";
	},
	
	onCleanFont: function()	{
		$('.bkp_post_content').find('[style]').each(function(index, value) {
			$(value).attr('style', '');
		});
	}
}).implement(PluginInterface);
FocusDetectorPlugin = Class.extend({
	init: function()	{
		this.name = "FocusDetectorPlugin";
	},
	
	onAttachFocusDetection: function(eventData)	{
		var target = eventData.target;
		var defaultValue = eventData.defaultValue;
		$(target).val(defaultValue);
		$(target).addClass('joo-non-focus');
		$(target).blur(function() {
			if ($(target).val() == '')	{
				$(target).val(defaultValue);
				$(target).addClass('joo-non-focus');
			}
		});
		$(target).focus(function() {
			if ($(target).hasClass('joo-non-focus'))	{
				$(target).val('');
				$(target).removeClass('joo-non-focus');
			}
		});
	}
}).implement(PluginInterface);
AutocompleteQuestionPlugin = Class.extend({
	init: function()	{
		this.name = "AutocompleteQuestionPlugin";
	},
	
	onHtmlRendered: function()	{
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent('AttachFocusDetection', {'target': $('#to'), 'defaultValue': 'Nhập vào từ khóa cho câu hỏi bạn muốn tìm'});
		$("#to").autocomplete({
			//define callback to format results
			source: function(req, add){
				var reservedTerm = req.term;
				var str = "";
				$("#friends span").each(function(){
					str += "," + $(this).contents().filter(function() { return this.nodeType == 3;}).text().trim();
				});
				req.filter = str.substring(1);
				req.term = req.term;

				var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
//				root = "http://localhost/bkprofile/index.php/";
				//pass request to server
				$.getJSON(root+"ajax/autocomplete-question?", req, function(data) {
					
					//create array for response objects
					var suggestions = [];
					////console.log(data)
					//process response
					$.each(data, function(i, val){
						if (val.expertise != null)								
							suggestions.push(val.expertise + "##a");
						if (val.question != null){
							var str = val.question_id + "##" +val.question;
							for (var i=0; i<val.catchwords.length; i++){
								if (val.catchwords[i] !== "null"){
									str += "##" + val.catchwords[i];
								}
							}
							str += "##a";
							//console.log(str);
							suggestions.push(str);
						}
							
					});
					
					suggestions.push('Đặt câu hỏi mới: "' + reservedTerm + '"');
					//pass array to callback
					add(suggestions);
				});
			},
			
			//define select handler
			select: function(e, ui) {
				
				//create formatted friend
				var friend = ui.item.value;
				if (ui.item.test === "expertise"){
					var span = $("<span>").text(friend);
					var a = $("<a>").addClass("remove").attr({
							href: "javascript:",
							title: "Remove " + friend
						}).text("x").appendTo(span);
					
					//add friend to friend div
					span.insertBefore("#to");
					var w = 0;
					$("#friends span").each(function(){
						w += $(this).outerWidth(true);
					});
					var adaptive_width = $("#friends").width() - w;
					var min = 120;
					if (adaptive_width < min){
						adaptive_width = $("#friends").width();
					}
					$("#to").width(adaptive_width);
					
				} else{
					if (friend.search("Đặt câu hỏi mới:")>=0){
						friend = friend.substr(16).trim();
						makeQuestion(friend);
					} else{
						var tmp = null;
						
						try {
							tmp = $("a[question='"+escape(friend)+"']");	
						} catch (e) {
							// TODO: handle exception
							//console.log("hello");
						}
						moveToAQuestion(tmp.attr("question_id"));
					}
						
				}
			},
			
			//define select handler
			change: function() {
				
				//prevent 'to' field being updated and correct position
				$("#to").css("top", 2);
			}
		});
		
		//add click handler to friends div
		$("#friends").click(function(){
			
			//focus 'to' field
			$("#to").focus();
		});
		
		//add live handler for clicks on remove links
		$(".remove", document.getElementById("friends")).live("click", function(){
		
			//remove current friend
			$(this).parent().remove();
			
			//correct 'to' field position
			if($("#friends span").length === 0) {
				$("#to").css("top", 0);
			}				
		});
	}
}).implement(PluginInterface);

function onClickQuestion(){
	var str = "";
	$("#friends span").each(function(){
		str += $(this).contents().filter(function() { return this.nodeType == 3;}).text().trim() + " ";
	});
	str += $("#to").val();
	
	var subject = SingletonFactory.getInstance(Subject);
    var request = new Request("Search","donganh",{"type":"Knowledge", "query":str});
    subject.notifyEvent('RequestRoute', request);
}

function moveToAQuestion(question_id){
	var qid = question_id;
	var subject = SingletonFactory.getInstance(Subject);
    var request = new Request("Question","donganh",{"qid":qid});
    subject.notifyEvent('RequestRoute', request);
}


function makeQuestion(ques){
	var app = SingletonFactory.getInstance(Application);
	var subject = SingletonFactory.getInstance(Subject);
	var logined = app.getSystemProperties().get("user.login");
	
//	if(logined != 1){
//		subject.notifyEvent("NeedLogin");
//	} else {
		var container = SingletonFactory.getInstance(PortletContainer);
		var portletMeta = container.getPortletMetaByName("AskNonTargetQuestionPortlet");
		portletMeta.active = true;
		var eventData = {};
		eventData.question = ques.substring(1, ques.length-1);
		portletMeta.portlet.showPortlet(eventData);
//	}
}

/*$(function(){
	$("#to").keyup(function(event){
		  if(event.keyCode == 13){
		    onClickQuestion();
		  }
		});
});

$(function(){
	$("#to").keypress(function(event){
		return !(window.event && window.event.keyCode == 13);
		});
});
*/
AutocompletePersonPlugin = Class.extend({
	init: function()	{
		this.name = "AutocompletePersonPlugin";
	},
	
	onHtmlRendered: function()	{
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent('AttachFocusDetection', {'target': $('#toPerson'), 'defaultValue': 'Nhập vào từ khóa cho người bạn muốn tìm'});
		//attach autocomplete
		$("#toPerson").autocomplete({
			//define callback to format results
			source: function(req, add){
				var reservedTerm = req.term;
				var str = "";
				$("#friendsPerson span").each(function(){
					str += "," + $(this).contents().filter(function() { return this.nodeType == 3;}).text().trim();
				});
				req.filter = str.substring(1);
				req.term = req.term;

				var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
//				root = "http://localhost/bkprofile/index.php/";
				//pass request to server
				$.getJSON(root+"ajax/autocomplete-person?", req, function(data) {
					
					//create array for response objects
					var suggestions = [];
					////console.log(data)
					//process response
					$.each(data, function(i, val){
						if (val.expertise != null)								
							suggestions.push(val.expertise + "##a");
						if (val.person != null){
							var str = 0 + "##" +val.person;
							if (val.catchwords != null){
								for (var i=0; i<val.catchwords.length; i++){
									if (val.catchwords[i] !== "null"){
										str += "##" + val.catchwords[i];
									}
								}
							}
							str += "##a";
							//console.log(str);
							suggestions.push(str);
						}
							
					});
					
					//pass array to callback
					add(suggestions);
				});
			},
			
			//define select handler
			select: function(e, ui) {
				
				//create formatted friend
				var friend = ui.item.value;
				if (ui.item.test === "expertise"){
					var span = $("<span>").text(friend);
					var a = $("<a>").addClass("remove").attr({
							href: "javascript:",
							title: "Remove " + friend
						}).text("x").appendTo(span);
					
					//add friend to friend div
					span.insertBefore("#toPerson");
					var w = 0;
					$("#friendsPerson span").each(function(){
						w += $(this).outerWidth(true);
					});
					var adaptive_width = $("#friendsPerson").width() - w;
					var min = 120;
					if (adaptive_width < min){
						adaptive_width = $("#friendsPerson").width();
					}
					$("#toPerson").width(adaptive_width);
					
				} else{
						onClickPerson();
				}
			},
			
			//define select handler
			change: function() {
				
				//prevent 'to' field being updated and correct position
				$("#toPerson").css("top", 2);
			}
		});
		
		//add click handler to friends div
		$("#friendsPerson").click(function(){
			
			//focus 'to' field
			$("#toPerson").focus();
		});
		
		//add live handler for clicks on remove links
		$(".remove", document.getElementById("friendsPerson")).live("click", function(){
		
			//remove current friend
			$(this).parent().remove();
			
			//correct 'to' field position
			if($("#friendsPerson span").length === 0) {
				$("#toPerson").css("top", 0);
			}				
		});
		
		$("#to").keypress(function(event){
			return !(window.event && window.event.keyCode == 13);
		});
	}
}).implement(PluginInterface);

function onClickPerson(){
	var str = "";
	$("#friendsPerson span").each(function(){
		str += $(this).contents().filter(function() { return this.nodeType == 3;}).text().trim() + " ";
	});
	str.trim();
	str += $("#toPerson").val();
	var subject = SingletonFactory.getInstance(Subject);
    var request = new Request("Search","donganh",{"type":"person-search", "query":str});
    subject.notifyEvent('RequestRoute', request);
}
PaginationPlugin = Class.extend({
	init: function()	{
		this.name = "PaginationPlugin";
		this.pageLinks = Array();
		this.numPages = null;
		this.numDocs = null;
		this.rows = 10;
		this.curPage = 0;
		this.paginationPage = 0;
	},
	
	onFetchPaginationLink: function(eventData)	{
		this.numDocs = eventData.numDocs;
		this.rows = eventData.rows;
		this.curPage = eventData.curPage;
		this.request = eventData.request;
		$(eventData.placeholder).append(this.fetchPageLink());
	},
	
	onPaginationOnclick: function(pagination)	{
		this.request.setParam('pagination',  pagination);
		var sbj = SingletonFactory.getInstance(Subject);
		sbj.notifyEvent('RequestRoute', this.request);
	},
	
	fetchPageLink: function(){
		var result = $("<div></div>");
		var numPages = Math.ceil(this.numDocs / this.rows);
		if(numPages == 0){
			numPages = 1;
		}
		var curPage = parseInt(this.curPage); 
		var pageLinks = Array();
		if (curPage > numPages){
			curPage = numPages;
		}
		if (curPage <= 0){
			curPage = 1;
		}
		
		for(var x = 1; x <= numPages; x ++) {
			if (x == curPage) {
				var objParam = {};
				objParam.content = x;
				pageLinks[x-1] = tmpl("CommonPortlet-NavCurrent",objParam);
			} else {
				var objParam = {};
				objParam.content = x;
				objParam.page = x;
				pageLinks[x-1] = tmpl("Pagination-NavOther",objParam);
			}
		}
		
		if (curPage > 1 && curPage <= pageLinks.length){
			var objParam = {};
			objParam.page = curPage-1;
			objParam.content = "&#171 Trước&nbsp;";
			result.append(tmpl("Pagination-NavOther",objParam));
		}
		
		for (var key= curPage-11; key <= curPage+9; key++ ) {
			if (key<0) continue;
			if (key>= pageLinks.length) continue;
			if (key == curPage)
				result.append(pageLinks[key]);
			else
				result.append(pageLinks[key]);
		}		
		
		if(curPage < pageLinks.length){
			var objParam = {};
			objParam.page = curPage+1;
			objParam.content = "&nbsp;Sau&nbsp;&#187";
			result.append(tmpl("Pagination-NavOther",objParam));
		}
		return result;
	}
}).implement(PluginInterface);
AnswerShowBioPlugin = Class.extend({
	init: function()	{
		this.name = "AnswerShowBioPlugin";
	},
	
	onBegin: function()	{
		this.catches = undefined;
	},
	
	onShowBio: function(eventData)	{
		var memcached = SingletonFactory.getInstance(Memcached);
		var keyToStore = "question.catchword";
		if (eventData.qid != this.qid)	{
			this.catches = undefined;
		}
		memcached.clear(keyToStore);
		this.qid = eventData.qid;
		var obj = this;
		$('.extension-point[extensionName="AnswerProfileName"]').each(function(index, value) {
			if ($(value).find('div[flag="AnswerShowBio"]').length > 0)	{
				return;
			}
			$(value).append('<div flag="AnswerShowBio"></div>');
			var uid = $(value).attr('extensionId');
			if (obj.catches == undefined)	{
				obj.onAjax('question', 'get-all-catchwords-question', {'qid': obj.qid}, 'GET', {
					'onSuccess': function(ret)	{
						memcached.store(keyToStore, ret);
						obj.catches = ret;
						obj.renderBio(value, uid);
					}
				});
			} else {
				obj.renderBio(value, uid);
			}
		});
	},
	
	renderBio: function(value, uid)	{
		var obj = this;
		this.onAjax('ajax', 'get-all-expertises', {'id': uid}, 'GET', {
			'onSuccess': function(ret)	{
				for(var i in obj.catches)	{
					var cat = obj.catches[i];
					var catId = cat.id;
					for (var j in ret)	{
						var retJ = ret[j];
						var retJContent = retJ.content;
						for (var k in retJContent)	{
							var retJContentK = retJContent[k];
							if (catId == retJContentK.id)	{
								var explanation = retJContentK.expertiseExplanation;
								$(value).prepend(tmpl('AnswerShowBioTmpl', {'content': explanation}));
								return;
							}
						}
					}
				}
			}
		}, true, 300000);
	}
}).implement(PluginInterface).implement(AjaxInterface);

AnswerEditBioPlugin = Class.extend({
	init: function()	{
		this.name = "AnswerEditBioPlugin";
	},
	
	onBegin: function()	{
		this.catches = undefined;
	},
	
	onRenderBioEditLink: function(eventData)	{
		var qid = eventData.qid;
		$('.extension-point[extensionName="AnswerProfileName"]').each(function(index, value) {
			if ($(value).find('div[flag="AnswerEditBio"]').length > 0)	{
				return;
			}
			var properties = SingletonFactory.getInstance(Application).getSystemProperties();
			var loggedIn = properties.get('user.login');
			if (loggedIn == 1)	{
				var userID = properties.get('user.id');
				var answerUID = $(value).attr('extensionID');
				if (userID == answerUID)	{
					$(value).append(tmpl('AnswerEditBioTmpl', {'qid':qid}));
				}
			}
		});
	},
	
	onEditBioClick: function(eventData)	{
		this.qid = eventData.qid;
		var obj = this;
		if (this.catches == undefined)	{
			var keyToGet = "question.catchword";
			var memcached = SingletonFactory.getInstance(Memcached);
			var catches = memcached.retrieve(keyToGet);
			if (catches != undefined)	{
				this.catches = catches;
				this.prepareShowingBioEditor();
			} else {
				obj.onAjax('question', 'get-all-catchwords-question', {'qid': obj.qid}, 'GET', {
					'onSuccess': function(ret)	{
						memcached.store(keyToGet, ret);
						obj.catches = ret;
						obj.prepareShowingBioEditor();
					}
				});
			}
		} else {
			this.prepareShowingBioEditor();
		}
	},
	
	prepareShowingBioEditor: function()	{
		var obj = this;
		var memcached = SingletonFactory.getInstance(Memcached);
		var currentExpertises = memcached.retrieve('user.expertises');
		this.currentExpertises = currentExpertises;
		if (currentExpertises == undefined)	{
			this.onAjax('ajax', 'get-all-expertises', {}, 'GET', {
				'onSuccess': function(ret)	{
					memcached.store('user.expertises', ret);
					obj.currentExpertises = ret;
					obj.showBioEditor();
				}
			}, true, 300000);
		} else {
			this.showBioEditor();
		}
	},
	
	showBioEditor: function()	{
		var obj = this;
		var expToShow = Array();
		var ret = obj.currentExpertises;
		for(var i in obj.catches)	{
			var found = false;
			var cat = obj.catches[i];
			var catId = cat.id;
			for (var j in ret)	{
				var retJ = ret[j];
				var retJContent = retJ.content;
				for (var k in retJContent)	{
					var retJContentK = retJContent[k];
					if (catId == retJContentK.id)	{
						if (retJContent[k].expertiseExplanation == undefined)
							retJContent[k].expertiseExplanation = "";
						var plhd = tmpl('AnswerBioEditorExplanationTmpl', {'expertiseName':retJContent[k].expertiseName, 'expertiseExplanation':retJContent[k].expertiseExplanation});
						expToShow.push({'id':retJContentK.id,'expertiseName': retJContent[k].expertiseName, 'expertisePlaceholder': plhd});
						found = true;
					}
				}
			}
			if (!found)	{
				var plhd = tmpl('AnswerBioEditorExplanationTmpl', {'expertiseExplanation': undefined, 'expertiseName':cat.catchword});
				expToShow.push({'id':cat.id,'expertiseName': cat.catchword, 'expertisePlaceholder': plhd});
			}
		}
		if (expToShow.length == 0)	{
			$.facebox('Câu hỏi hiện tại không thuộc chủ đề nào. Do đó bạn chưa thể thay đổi chú thích ngay bây giờ');
		} else {
			$.facebox(tmpl('AnswerBioEditorTmpl', {'expertises':expToShow}));
		}
	},
	
	onBioEditorEditClick: function(event)	{
		var target = event.event.target;
		var mode = event.mode;
		var parent = $(target).parent();
		var oldHtml = $(parent).find('.explanationPlaceholder').html();
		$(parent).html(tmpl('AnswerBioEditorExplanationEditTmpl', {'content': oldHtml, 'mode':mode}));
		$(parent).find('textarea').focus();
	},
	
	onBioEditCancelClick: function(event)	{
		var target = event.target;
		var parent = $(target).parent().parent();
		var textBox = $(parent).find('textarea');
		$(parent).html(tmpl('AnswerBioEditorExplanationTmpl', {'expertiseExplanation':$(textBox).attr('oldVal'), 'expertiseName':$(parent).attr('expertiseName')}));
	},
	
	onBioEditUpdateClick: function(event)	{
		var target = event.event.target;
		var mode = event.mode;
		var parent = $(target).parent().parent();
		var textBox = $(parent).find('textarea');
		var newVal = $(textBox).val();
		var oldVal = $(textBox).attr('oldVal');
		if (newVal == oldVal)	{
			$(parent).html(tmpl('AnswerBioEditorExplanationTmpl', {'expertiseExplanation':oldVal, 'expertiseName':$(parent).attr('expertiseName')}));
		} else {
			var id = $(parent).attr('expertiseID');
			if (mode == 'update')	{
				this.onAjax('ajax', 'update-single-expertise', {'id': id, 'explanation':newVal}, 'POST', {});
			} else {
				this.onAjax('ajax', 'add-single-expertise', {'id': id, 'explanation':newVal}, 'POST', {});
			}
			$(parent).html(tmpl('AnswerBioEditorExplanationTmpl', {'expertiseExplanation':newVal, 'expertiseName':$(parent).attr('expertiseName')}));
		}
	}
}).implement(PluginInterface).implement(AjaxInterface);
/**
 * 
 */

ExpertisePlugin = Class.extend({
	init: function()	{
		this.name = "ExpertisePlugin";
	},
	
	onHtmlRendered: function(eventData)	{
		this.render();
	},
	
	onHtmlUpdated: function(eventData)	{
		this.render();
	},
	
	onExpertiseTitleHover: function(eventData)	{
		var target = eventData.target;
		var id = $(target).parent().attr('extensionId');
//		this.onAjax('catchword', 'get-catchword-description', {'id': id}, 'GET',	{
//			'onSuccess': function(ret)	{
//				
//			}
//		});
	},
	
	render: function(eventData)	{
		$('.extension-point[extensionName="ExpertiseTitle"]').each(function(index, value)	{
			if ($(value).find('div[flag="ExpertisePlugin"]').length > 0)
				return;
			var old = $(value).html();
			var eid = $(value).attr('extensionId');
			$(value).html("<a href='#page/Topic/id/"+eid+"' onmouseover='generateEvent(&apos;ExpertiseTitleHover&apos;, event)'>"+old+"</a><div flag='ExpertisePlugin'></div>");
		});
		
		$('.extension-point[extensionName="InterestTitle"]').each(function(index, value)	{
			if ($(value).find('div[flag="ExpertisePlugin"]').length > 0)
				return;
			var old = $(value).html();
			var eid = $(value).attr('extensionId');
			$(value).html("<a href='#page/Topic/id/"+eid+"' onmouseover='generateEvent(&apos;ExpertiseTitleHover&apos;, event)'>"+old+"</a><div flag='ExpertisePlugin'></div>");
		});
		
//		$('.extension-point[extensionName="ExpertiseContextTitle"]').each(function(index, value)	{
//			var old = $(value).html();
//			$(value).html("<a class='strong' href='http://javavietnam.org' title='Java is the best programming language'>"+old+"</a>");
//		});
	}
}).implement(PluginInterface).implement(AjaxInterface);

ToggleHeadingPlugin = Class.extend({
	init: function()	{
		this.name = "ToggleHeadingPlugin";
	},
	
	onHtmlRendered: function(eventData)	{
		this.render();
	},
	
	onHtmlUpdated: function(eventData)	{
		this.render();
	},
	
	render: function(eventData)	{
		$('.extension-point[extensionName="HeadingPlaceholderRight"]').each(function(index, value)	{
			if ($(value).find('[flag="toggleHeadingFlag"]').length > 0)	{
				return;
			}
			var target = $(value).parent().parent().parent().parent().siblings('.children_container');
			$(value).append(old+'<img flag="toggleHeadingFlag" src="/bkprofile/styles/images/toggle_up_dark.png" style="vertical-align: middle; margin-right: 5px; cursor: pointer; position: relative; float: right;" onclick="generateEvent(&apos;ToggleHeading&apos;, &apos;'+$(target).attr('id')+'&apos;);" alt="Click here for more information" id="img-p3">');
		});
	},
	
	onToggleHeading: function(eventData)	{
		$('#'+eventData).toggle();
	}
}).implement(PluginInterface);

TemplateDebugPlugin = Class.extend({
	init: function()	{
		this.rendered = false;
		this.name = "TemplateDebugPlugin";
	},
	
	onHtmlRendered: function(eventData)	{
		if (this.rendered)
			return;
		$.each($('.portlet-container'), function(index, value)	{
			$(value).append('<div>Portlet Container: '+$(value).attr('id')+'</div>');
		});
		this.rendered = true;
	}
}).implement(PluginInterface);

TextAreaAutoExpandPlugin = Class.extend({
	init: function()	{
		this.name = "TextAreaAutoExpandPlugin";
	},

	onExpandTextArea: function(eventData)	{
		var value = eventData.target;
		if ($(value).attr('flag') == 'TextAreaAutoExpand')
			return;
		$(value).attr('flag', 'TextAreaAutoExpand');
		$(value).TextAreaExpander();
	}
}).implement(PluginInterface);

FormatterPlugin = Class.extend({
	init: function()	{
		this.name = "FormatterPlugin";
	},
	
	onNeedFormatting: function(eventData)	{
		$('.extension-point[extensionName="Placeholder"]').each(function(index, value)	{
//			//console.log('extending '+$(value).parent().parent().attr('id'));
			if ($(value).attr('flag') == 'formatted')	{
				return;
			}
			
			//adjust depth
			var depth = $(value).attr('depth');
			if (depth == undefined) depth = 0;
			if (depth > 0) depth --;
			if (depth > 3) depth = 3;
			$(value).attr('style', 'margin-left: '+(depth*95)+'px');
			var state = $(value).attr('state');
			var type = $(value).attr('type');
			var key = $($(value).find('.sub_keyword.keyword')[0]).html();
			var v = $($(value).find('.content')[0]).html();
			
			var formatter = SingletonFactory.getInstance(FormatterFactory).getFormatter(type, state);
			if (formatter != undefined)	{
				formatter.format(key, v, value);
			}
			
			$(value).attr('flag', 'formatted');
		});
		
		$(".customDatePicker input").each(function(index, value)	{
			$(value).datepicker({dateFormat:"dd, M yy", 
				changeMonth: true,
				changeYear: true,
				yearRange:'-100:+10',
				showOn: "button",
				buttonImage: "static/images/cal.png",
				buttonImageOnly: true,
				buttonText: "Choose date",
				onSelect: function(dateText, inst) {$(value).attr("modified","true")}
			});
		});
	},
	
	onAddToken: function(eventData)	{
//		//console.log(eventData.keyCode);
		if (eventData.keyCode == 13)	{
			var target = eventData.target;
			var partial = {};
			partial.content = $(target).val();
			partial.oid = "";
			var container = $(target).siblings('.tokenContainer').append(tmpl('ListPartial-Edit', partial));
			$(target).val('');
		}
	},
	
	onDelToken: function(eventData)	{
		var target = eventData.target;
		$(target).parent().remove();
	},
	
	onAddEmailToken: function(eventData)	{
		if (eventData.keyCode == 13)	{
			var target = eventData.target;
			var provider = $(target).siblings('select').find('option:selected').html();
			var partial = {};
			partial.oid = "";
			partial.content = $(target).val()+'@'+provider;
			var container = $(target).siblings('.tokenContainer').append(tmpl('ListPartial-Edit', partial));
			$(target).val('');
		}
	}
}).implement(PluginInterface);

FormatterFactory = Class.extend({
	getFormatter: function(type, state)	{
		var className = type+state+"Formatter";
		if (window[className] == undefined)	{
			//console.warn('Formatter '+type+'-'+state+' is not defined!');
			return undefined;
		} else {
			return new window[className	](state);
		}
	}
});

BaseFormatter = Class.extend({
	init: function()	{
		
	},
	
	format: function(key, value, placeholder)	{
		this.placeholder = placeholder;
		this.doFormat(key, value, placeholder);
	},
	
	doFormat: function(key, value, placeholder)	{
		$(placeholder).html(this.render(key, value));
	}
});

HeadingViewFormatter = BaseFormatter.extend({
	render: function(key, value)	{
		var obj = {};
		obj.keyword = key;
		obj.content = value;
		return tmpl('HeadingPlaceholder', obj);
	}
});

HeadingEditFormatter = HeadingViewFormatter.extend({});

NoneViewFormatter = BaseFormatter.extend({
	render: function(key, value)	{
		var obj = {};
		obj.keyword = key;
		return tmpl('NonePlaceholder', obj);
	}
});

NoneEditFormatter = NoneViewFormatter.extend({});

ListViewFormatter = BaseFormatter.extend({
	init: function()	{
		this.separator = ', ';
	},
	
	doFormat: function(key, value, placeholder)	{
		var keyword = $(placeholder).attr('name');
		var id = 'ListFormatter-'+keyword;
		var partial = {};
		partial.content = value;
		partial.oid = $(placeholder).parents('[rootname]:first').attr('oid');
		if (isNaN(partial.oid))	{
			partial.oid = "";
		}
		var fragment = this.buildFragment(partial);
		if (value == "" || $(placeholder).attr('mockup') == 'true')	{
			fragment = "";
		}
		
		//find the previous placeholder, because list is singleton
		if ($(placeholder).parents('.children_container:first').find('#'+id).length > 0)	{
			if (value == "" || $(placeholder).attr('mockup') == 'true')	{
				$(placeholder).remove();
				return;
			}
			$(placeholder).parents('.children_container:first').find('#'+id).find('.content').append(this.separator+fragment);
			$(placeholder).parent().parent().remove();
		} else {
			//not found, create new placeholder
			var obj = {};
			obj.id = id;
			obj.keyword = key;
			obj.content = fragment;
			var html = this.onRender(obj);
			$(placeholder).html(html);
		}
	},
	
	onRender: function(obj)	{
		return tmpl('ListPlaceholder', obj);
	},
	
	buildFragment: function(partial)	{
		return tmpl('ListPartial', partial);
	}
});

ListEditFormatter = ListViewFormatter.extend({
	init: function()	{
		this.separator = '';
	},
	
	onRender: function(obj)	{
		return tmpl('ListPlaceholder-Edit', obj);
	},
	
	buildFragment: function(partial)	{
		return tmpl('ListPartial-Edit', partial);
	}
});

NormalViewFormatter = BaseFormatter.extend({
	doFormat: function(key, value, placeholder)	{
		var obj = {};
		obj.keyword = key;
		obj.content = value;
		//find previous placeholder
		var keyword = $(placeholder).attr('name');
		if (this.checkDuplicate(keyword))	{
			obj.keyword = "";
		}
		obj.name = keyword;
		$(placeholder).html(this.onRender(obj));
	},
	
	checkDuplicate: function(keyword)	{
		return ($(this.placeholder).parent().parent().parent().find('.normal-formatter[name="'+keyword+'"]').length > 0);
	},
	
	onRender: function(obj)	{
		return tmpl('NormalPlaceholder', obj);
	}
});

NormalEditFormatter = NormalViewFormatter.extend({
	onRender: function(obj)	{
		return tmpl('NormalPlaceholder-Edit', obj);
	}
});

NormalLargeEditFormatter = NormalViewFormatter.extend({
	onRender: function(obj)	{
		return tmpl('NormalLargePlaceholder-Edit', obj);
	}
});

DateViewFormatter = NormalViewFormatter.extend({});

DateEditFormatter = NormalViewFormatter.extend({
	checkDuplicate: function(keyword)	{
		return ($(this.placeholder).parent().parent().parent().find('.date-formatter[name="'+keyword+'"]').length > 0);
	},
	
	onRender: function(obj)	{
		return tmpl('DatePlaceholder-Edit', obj);
	}
});

EmailViewFormatter = NormalViewFormatter.extend({});

EmailEditFormatter = ListEditFormatter.extend({
	init: function()	{
		this.separator = '';
	},
	
	onRender: function(obj)	{
		var params = $(this.placeholder).attr('params');
		var providers = params.split(',');
		var objProviders = {};
		objProviders.providers = providers;
		obj.select = tmpl('EmailProviders-Edit', objProviders);
		return tmpl('EmailPlaceholder-Edit', obj);
	}
});

EnumViewFormatter = NormalViewFormatter.extend({});

EnumEditFormatter = BaseFormatter.extend({
	doFormat: function(key, value, placeholder)	{
		var params = $(placeholder).attr('params');
		var choices = params.split(',');
		var str = "";
		for(var i in choices)	{
			var choice = choices[i];
			var checked = "";
			if (choice == value)	{
				checked = "checked";
			}
			var obj = {};
			obj.checked = checked;
			obj.choice = choice;
			obj.name = $(placeholder).attr('name');
			str += tmpl('EnumPartial-Edit', obj);
		}
		var enumObj = {};
		enumObj.content = str;
		enumObj.keyword = key;
		$(placeholder).html(tmpl('EnumPlaceholder-Edit', enumObj));
	}
});

UserTabGeneratorPlugin = Class.extend({
	init: function()	{
		this.name = "UserTabGeneratorPlugin";
		this.ids = new Array("User","UserQuestion","UserTarget","UserAnswer");
	},
	
	onUserTabGeneratorChange: function(eventData){
		var id = eventData.id;
		var curObj = $("#"+id);
		var curClass = curObj.attr("class");
		if(curClass == "bkp_userTabActivated"){
			return;
		}
		
		curObj.siblings().removeClass().addClass("bkp_userTabDeactivated");
		curObj.removeClass().addClass("bkp_userTabActivated");
	},
	
	onPageBegan: function()	{
		var request = SingletonFactory.getInstance(Page).getRequest();
		var page = request.getParam("page");
		var plugin = this;
		if ($('#UserTabGeneratorPlaceholder').length <= 0)	{
			var template = $(tmpl('UserTabGeneratorPlaceholder-Tmpl', {}));
			var original = template.clone();
			var count = 0;
			var templateA = $(template).find(".userTab a").each(function(){
				count++;
				if(plugin.ids[count-1] != page){
					$(this).addClass("bkp_userTabDeactivated");
				} else {
					$(this).addClass("bkp_userTabActivated");
				}
				var curID = "userTab-" + count;
				$(this).attr("id",curID);
				$(this).attr("onClick","generateEvent('UserTabGeneratorChange',{id:'"+curID+"'})");
			});
			var template = $(template).children(".userTab").empty().append(templateA);
			template = original.empty().append(template);
			$('div.extension-point[extensionName="MiddleMain"]').append(template);
		}else{
			for( var i=0; i<this.ids.length; i++ )	{
				if($('#userTab-'+(i+1)).hasClass("bkp_userTabActivated")){
					$('#userTab-'+(i+1)).removeClass("bkp_userTabActivated");
				}
				if($('#userTab-'+(i+1)).hasClass("bkp_userTabDeactivated")){
					$('#userTab-'+(i+1)).removeClass("bkp_userTabDeactivated");
				}
			}
			
			for( var i=0; i<this.ids.length;i++ )	{
				if(this.ids[i] == page){
					$('#userTab-'+(i+1)).addClass("bkp_userTabActivated");
				}else{
					$('#userTab-'+(i+1)).addClass("bkp_userTabDeactivated");
				}
			}
		}
	},
	
	onEnd: function()	{
		if ($('#UserTabGeneratorPlaceholder').length > 0)
			$('#UserTabGeneratorPlaceholder').remove();
	}
}).implement(PluginInterface);

ProfileTabGeneratorPlugin = Class.extend({
	init: function()	{
		this.name = "ProfileTabGeneratorPlugin";
		this.ids = new Array("Profile","ProfileQuestion","ProfileTarget","ProfileAnswer");
	},
	
	onReloadPlugin: function()	{
		//remove old tab
		if ($('#ProfileTabGeneratorPlaceholder').length > 0)
			$('#ProfileTabGeneratorPlaceholder').remove();
		this.renderTab();
	},
	
	onUserTabGeneratorChange: function(eventData){
		var id = eventData.id;
		var curObj = $("#"+id);
		var curClass = curObj.attr("class");
		if(curClass == "bkp_userTabActivated"){
			return;
		}
		
		curObj.siblings().removeClass().addClass("bkp_userTabDeactivated");
		curObj.removeClass().addClass("bkp_userTabActivated");
	},
	
	onPageBegan: function()	{
		this.renderTab();
	},
	
	renderTab: function()	{
		var request = SingletonFactory.getInstance(Page).getRequest();
		var params = request.getParams();
		var page = request.getParam("page");
		if ($('#ProfileTabGeneratorPlaceholder').length <= 0)	{
			var id = params['id'] || undefined;
			var objParam = {};
			if (id != undefined){
				objParam.id = id;
			}
			
			var template = $(tmpl('ProfileTabGeneratorPlaceholder-DATmpl', objParam));
			var original = template.clone();
			var count = 0;
			var plugin = this;
			var templateA = $(template).find(".userTab a").each(function(){
				count++;
				if(plugin.ids[count-1] != page){
					$(this).addClass("bkp_userTabDeactivated");
				} else {
					$(this).addClass("bkp_userTabActivated");
				}
				var curID = "userTab-" + count;
				$(this).attr("id",curID);
				$(this).attr("onClick","generateEvent('UserTabGeneratorChange',{id:'"+curID+"'})");
			});
			
			var template = $(template).children(".userTab").empty().append(templateA);
			template = original.empty().append(template);
			$('div.extension-point[extensionName="MiddleMain"]').append(template);
			
		} else{
			for( var i=0; i<this.ids.length; i++ )	{
				if($('#userTab-'+(i+1)).hasClass("bkp_userTabActivated")){
					$('#userTab-'+(i+1)).removeClass("bkp_userTabActivated");
				}
				if($('#userTab-'+(i+1)).hasClass("bkp_userTabDeactivated")){
					$('#userTab-'+(i+1)).removeClass("bkp_userTabDeactivated");
				}
			}
			
			for( var i=0; i<this.ids.length;i++ )	{
				if(this.ids[i] == page){
					$('#userTab-'+(i+1)).addClass("bkp_userTabActivated");
				}else{
					$('#userTab-'+(i+1)).addClass("bkp_userTabDeactivated");
				}
			}
		}
	},
	
	onEnd: function()	{
		if ($('#ProfileTabGeneratorPlaceholder').length > 0)
			$('#ProfileTabGeneratorPlaceholder').remove();
	}
}).implement(PluginInterface);

UserControlBoxPlugin = Class.extend({
	init: function()	{
		this.name = "UserControlBoxPlugin";
	},
	
	onSystemPropertyChanged: function(eventData)	{
		if (eventData == 'user.login')	{
			this.setupUserBox();
		}
	},
	
	onBegin: function(eventData)	{
		var properties = SingletonFactory.getInstance(Application).getSystemProperties();
		var loggedIn = properties.get('user.login');
		var obj = this;
//		if (loggedIn == undefined)	{
			this.onAjax('ajax', 'check-user-status', {}, 'GET', 
					{'onSuccess': function(ret)	{
						if (ret == 0)	{
							properties.set('user.login', 0, true);
						} else {
							properties.set('user.login', 1, true);
							properties.set('user.id', ret.userid, true);
							properties.set('user.name', ret.name, true);
						}
						obj.setupUserBox();
					}});
//		}
//		this.setupUserBox();
	},

	setupUserBox: function()	{
		var systemProperties = SingletonFactory.getInstance(Application).getSystemProperties();
		var loggedIn = systemProperties.get('user.login');
		var obj = {};
		var navs = Array();
		navs.push({'page': 'Home', 'label': 'Trang chủ', 'title': 'Trang chủ của BKProfile'});
		navs.push({'page': 'Feedback', 'label': 'Góp ý', 'title': 'Góp ý, thông báo lỗi cho hệ thống BKProfile'});
		if (loggedIn == true)	{
			var name = systemProperties.get('user.name');
			navs.push({'page': 'User', 'label': name, 'title': 'Trang cá nhân của bạn'});
			navs.push({'page': 'Logout', 'label': 'Đăng xuất', 'title': 'Đăng xuất khỏi tài khoản của bạn'});
		} else {
			navs.push({'page': 'Login', 'label': 'Đăng nhập', 'title': 'Đăng nhập vào BKProfile'});
			navs.push({'page': 'Register', 'label': 'Đăng ký', 'title': 'Đăng ký tài khoản tại BKProfile'});
		}
		obj.navs = navs;
		if ($('#UserControlBoxPlugin').length <= 0)	{
			$('div.extension-point[extensionName="TopRight"]').append(tmpl('UserControlBoxPluginContainer', {}));
		}
		$('#UserControlBoxPlugin').html(tmpl('UserControlBoxPluginTmpl', obj));
	},
	
	onEnd: function()	{
		if ($('#UserControlBoxPlugin').length > 0)
			$('#UserControlBoxPlugin').remove();
	}
}).implement(PluginInterface).implement(AjaxInterface);

UserLogoutPlugin = Class.extend({
	init: function()	{
		this.name = "UserLogoutPlugin";
	},
	
	onPageBegan: function()	{
		this.onAjax('ajax', 'logout', {}, 'POST', {
			'onSuccess': function(ret)	{
				var systemProperties = SingletonFactory.getInstance(Application).getSystemProperties();
				systemProperties.set('user.login', 0, true);
				systemProperties.set('user.id', undefined, true);
				var request = new Request("Home");
				var subject = SingletonFactory.getInstance(Subject);
				subject.notifyEvent("RequestRoute", request);
			}
		});
	}
}).implement(PluginInterface).implement(AjaxInterface);
ExpertiseEditorPlugin = Class.extend({
	
init: function()	{
	this.name = "ExpertiseEditorPlugin";
},

onRenderExpertiseEditor: function(eventData)	{
	this.placeholder = eventData.placeholder;
	var namespace = eventData.namespace;
	$(this.placeholder).html(tmpl('ExpertiseSubplaceholder', {}));
	var expertiseMsg = 'Kinh nghiệm';
	var followMsg = 'Lĩnh vực quan tâm';
	$(this.placeholder).find('#ProfileExpertise').html(tmpl('ListContainer', {'id':'ListExpertise', 'name': 'expertise', 'keyword':expertiseMsg, 'namespace':namespace}));
	$(this.placeholder).find('#ProfileFollow').html(tmpl('ListContainer', {'id':'ListInterestedArea','name': 'interested-area', 'keyword':followMsg, 'namespace':namespace}));
	
	var addExpertiseInput = $(this.placeholder).find('[container="ListExpertise"] input.ui-autocomplete-input');
	var addInterestInput = $(this.placeholder).find('[container="ListInterestedArea"] input.ui-autocomplete-input');
	
	//setup autocomplete
	var eventData = {};
	eventData.focusCallback = "RegisterAddExpertiseFocus";
	eventData.selectCallback = "RegisterAddExpertiseSelect";
	eventData.autocompleteObject = addExpertiseInput;
	eventData.autocompleteSource = "catchword/autocomplete-all-catchwords";
	var subject = SingletonFactory.getInstance(Subject);
	subject.notifyEvent('NeedAutocomplete', eventData);
	
	var eventData = {};
	eventData.focusCallback = "RegisterAddInterestFocus";
	eventData.selectCallback = "RegisterAddInterestSelect";
	eventData.autocompleteObject = addInterestInput;
	eventData.autocompleteSource = "catchword/autocomplete-all-catchwords";
	var subject = SingletonFactory.getInstance(Subject);
	subject.notifyEvent('NeedAutocomplete', eventData);
},

onCatchwordHelp: function(eventData)	{
	var str = '';
	if (eventData == 'ListExpertise')	{
		str = 'Bạn nên nhập đầy đủ kinh nghiệm của mình để người khác có thể dễ dàng kết nối đến bạn hơn';
	} else {
		str = 'Bạn nên nhập lĩnh vực quan tâm để chúng tôi có thể dễ dàng gợi ý cho bạn những câu hỏi mà bạn quan tâm';
	}
	$.facebox("<div class='expertiseTooltip'>"+str+"</div>");
},

onRegisterAddInterestFocus: function(eventData)	{
	var ui = eventData.ui;
	var addInterestInput = $(this.placeholder).find('[container="ListInterestedArea"] input.ui-autocomplete-input');
	$(addInterestInput).val(ui.item.label);
},

onRegisterAddInterestSelect: function(eventData)	{
	var ui = eventData.ui;
	var label = ui.item.label;
	var tmp = null;
	try {
		tmp = $("a[catch='"+escape(label)+"']");	
	} catch (e) {
		// TODO: handle exception
	}
	var value = tmp.attr("catch_id");
	var addInterestContainer = $(this.placeholder).find('[container="ListInterestedArea"] div.tokenContainer');
	var addInterestInput = $(this.placeholder).find('[container="ListInterestedArea"] input.ui-autocomplete-input');
	$(addInterestContainer).append(tmpl('TokenPartial', {'label':label, 'value':value}));
},

onRegisterAddExpertiseFocus: function(eventData)	{
	var ui = eventData.ui;
	var addExpertiseInput = $(this.placeholder).find('[container="ListExpertise"] input.ui-autocomplete-input');
	$(addExpertiseInput).val(ui.item.label);
},

onRegisterAddExpertiseSelect: function(eventData)	{
	var ui = eventData.ui;
	var label = ui.item.label;
	var tmp = null;
	try {
		tmp = $("a[catch='"+escape(label)+"']");	
	} catch (e) {
		// TODO: handle exception
	}
	var value = tmp.attr("catch_id");
	var addExpertiseContainer = $(this.placeholder).find('[container="ListExpertise"] div.tokenContainer');
	var addExpertiseInput = $(this.placeholder).find('[container="ListExpertise"] input.ui-autocomplete-input');
	$(addExpertiseInput).val('');
	$(addExpertiseContainer).append(tmpl('TokenPartial', {'label':label, 'value':value}));
}
}).implement(PluginInterface);

ExpertiseDeletePlugin = Class.extend({
	init: function()	{
		this.name = "ExpertiseDeletePlugin";
	},
	
	onHtmlUpdated: function(eventData)	{
		$('#effective-area .extension-point[extensionName="expertisePartial"]').each(function(index, value)	{
			if ($(value).attr('formatted') == 'expertiseDelete')
				return;
			$(value).attr('formatted', 'expertiseDelete');
			var obj = {};
			obj.id = $(value).attr('extensionId');
			$(value).append(tmpl('ExpertiseDelete', obj));
		});
	},
	
	onExpertiseDeleteButtonClick: function(eventData)	{
		var target = eventData.target;
		var id = $(target).attr('eid');
		this.onAjax('ajax', 'remove-single-expertise', {'id':id}, 'POST', 
				{'onSuccess': function(ret)	{
					$(target).parent().parent().remove();
				},
				'onFailure': function(){
					$.facebox('Hiện thời hệ thống không thể xóa mục này. Bạn vui lòng thử lại sau');
				}});
	}
}).implement(PluginInterface).implement(AjaxInterface);

ExpertiseVotePlugin = Class.extend({
	init: function()	{
		this.name = "ExpertiseVotePlugin";
	},
	
	onHtmlUpdated: function(eventData)	{
		var _this = this;
		var request = SingletonFactory.getInstance(Page).getRequest();
		$('#effective-area .extension-point[extensionName="expertisePartialLeft"]').each(function(index, value)	{
			if ($(value).find('.flag[flagName="expertiseVote"]').length > 0)
				return;
			var obj = {};
			obj.id = $(value).attr('extensionId');
			var profileid = request.getParam('id');
			_this.onAjax('catchword', 'get-user-expertise-vote', {'id':profileid, 'catchword':obj.id}, 'GET', {
				'onSuccess': function(ret)	{
					if ($(value).find('.flag[flagName="expertiseVote"]').length > 0)
						return;
					obj.vote = ret;
					$(value).append($('<div class="flag" flagName="expertiseVote"></div>'));
					$(value).append(tmpl('ExpertiseVote', obj));
				}
			}, true, 300000);
		});
	},
	
	onExpertiseDeleteButtonClick: function(eventData)	{
		var target = eventData.target;
		var id = $(target).attr('eid');
		this.onAjax('ajax', 'remove-single-expertise', {'id':id}, 'POST', 
				{'onSuccess': function(ret)	{
					$(target).parent().parent().remove();
				},
				'onFailure': function(){
					$.facebox('Hiện thời hệ thống không thể xóa mục này. Bạn vui lòng thử lại sau');
				}});
	}
}).implement(PluginInterface).implement(AjaxInterface);

ExpertiseEditPlugin = Class.extend({
	init: function()	{
		this.name = "ExpertiseEditPlugin";
	},
	
	onExpertiseEditableBlur: function(eventData)	{
		var target = eventData.target;
		var id = $(target).attr('eid');
		var explanation = $(target).val();
		var oldhtml = $(target).attr('oldhtml');
		if (oldhtml != explanation)	{
			var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
			$.post(root+'ajax/update-single-expertise', {'id': id, 'explanation': explanation});
		}
		$(target).parent().html($(target).val());
		$(target).removeClass('ui-editable-edit');
	},
	
	onHtmlUpdated: function(eventData)	{
		$('#effective-area .extension-point[extensionName="expertiseExplanation"]').each(function(index, value)	{
			if ($(value).attr('formatted') == 'expertiseExplanation')
				return;
			$(value).attr('formatted', 'expertiseExplanation');
			var obj = {};
			obj.id = $(value).attr('extensionId');
			$(value).addClass('editableLabel');
			$(value).bind('click', function(event)	{
				var target = event.target;
				var oldhtml = $(target).html().trim();
				var id = $(target).attr('eid');
				$(target).addClass('ui-editable-edit');
				$(target).html('<input eid='+id+' oldhtml="'+oldhtml+'" onblur="generateEvent(&apos;ExpertiseEditableBlur&apos;, event)" type="text" value="'+oldhtml+'">');
				$(target).find('input').focus();
			});
		});
	}
}).implement(PluginInterface);

InterestDeletePlugin = Class.extend({
	init: function()	{
		this.name = "InterestDeletePlugin";
	},
	
	onHtmlUpdated: function(eventData)	{
		$('#effective-area .extension-point[extensionName="InterestPartial"]').each(function(index, value)	{
			if ($(value).attr('formatted') == 'InterestDelete')
				return;
			$(value).attr('formatted', 'InterestDelete');
			var obj = {};
			obj.id = $(value).attr('extensionId');
			$(value).append(tmpl('InterestDelete', obj));
		});
	},
	
	onInterestDeleteButtonClick: function(eventData)	{
		var target = eventData.target;
		var id = $(target).attr('eid');
		var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
		$.post(root+'ajax/remove-single-interest',
			{'id': id}, function(ret)	{
				ret = $.parseJSON(ret);
				if (ret.result == 'error')	{
					$.facebox('Hiện thời hệ thống không thể xóa mục này. Bạn vui lòng thử lại sau');
				} else {
					$(target).parent().parent().remove();
				}
			});
	}
}).implement(PluginInterface);
/**
 * 
 */
UserCheckLoginPlugin = Class.extend({
	init: function()	{
		this.name = "UserCheckLoginPlugin";
	},
	
	onPageBegan: function()	{
		var properties = SingletonFactory.getInstance(Application).getSystemProperties();
		var loggedIn = properties.get('user.login', undefined);
		var root = properties.get('host.root');
		var subject = SingletonFactory.getInstance(Subject);
		if (loggedIn == undefined)	{
			//query to server
			this.onAjax('ajax', 'check-user-status', {'profile-id':this.profile_id}, 'POST', 
					{'onSuccess': function(ret)	{
						if (ret == 0)	{
							properties.set('user.login', 0, true);
							var request = new Request('Login', undefined, null);
							subject.notifyEvent("RequestRoute", request);
						} else {
							properties.set('user.login', 1, true);
							properties.set('user.id', ret.userid, true);
						}
					}});
		} else if (loggedIn == false)	{
			var request = new Request('Login', undefined, null);
			subject.notifyEvent("RequestRoute", request);
		}
	}
}).implement(PluginInterface);


UserLoginRequestPlugin = Class.extend({
	init: function()	{
		this.name = "UserLoginRequestPlugin";
		
		var properties = SingletonFactory.getInstance(Application).getSystemProperties();
		var loggedIn = properties.get('user.login', undefined);
		var root = properties.get('host.root');
		var subject = SingletonFactory.getInstance(Subject);
		if (loggedIn == undefined)	{
			//query to server
			$.ajax({url:root+'ajax/check-user-status',async:false, data: 
				{}, success: function(ret)	{
					//console.log("done");
					ret = $.parseJSON(ret);
					if (ret.result == 0)	{
						properties.set('user.login', 0, true);
					} else {
						properties.set('user.login', 1, true);
						properties.set('user.id', ret.userid, true);
					}
			}});
		}
	},
	
	onCheckLoginRequired: function(eventData){
		//console.log("onCheckLoginRequired == ");
		var request = SingletonFactory.getInstance(Page).getRequest();
		var app = SingletonFactory.getInstance(Application);
		if(request != undefined){
			app.getSystemProperties().set("request.callback", request)
		}
		
		var properties = SingletonFactory.getInstance(Application).getSystemProperties();
		var loggedIn = properties.get('user.login', undefined);
		var root = properties.get('host.root');
		var subject = SingletonFactory.getInstance(Subject);
		if (loggedIn == undefined)	{
			//query to server
			this.onAjax('ajax', 'check-user-status', {'profile-id':this.profile_id}, 'POST', 
					{'onSuccess': function(ret)	{
						if (ret == 0)	{
							properties.set('user.login', 0, true);
							var request = new Request('Login', undefined, null);
							subject.notifyEvent("RequestRoute", request);
						} else {
							properties.set('user.login', 1, true);
							properties.set('user.id', ret.userid, true);
						}
					}});
		} else if (loggedIn == false)	{
			var request = new Request('Login', undefined, null);
			subject.notifyEvent("RequestRoute", request);
		}
	}
}).implement(PluginInterface);


LoginSuccessRedirectPlugin = Class.extend({
	init: function()	{
		this.name = "LoginSuccessRedirectPlugin";
	},
	
	onLoginSuccess: function()	{
		var app = SingletonFactory.getInstance(Application);
		//FIXME: What is this? I don't remember :(
		var history = app.getSystemProperties().get("request.callback");
		var request = history != undefined ? history : new Request('Home', undefined, null);
		app.getSystemProperties().set("request.callback", undefined);
		var subject = new SingletonFactory.getInstance(Subject);
		subject.notifyEvent('RequestRoute', request);
	}
}).implement(PluginInterface);
ProfileEditTabPlugin = Class.extend({
	init: function()	{
		this.name = "ProfileEditTabPlugin";
	},

	onRenderProfileEditTab: function(eventData)	{
		var placeholder = eventData.placeholder;
		var tabs = eventData.tabs;
		var obj = {};
		obj.tabs = tabs;
		var tabMeta = tmpl('TabsMeta', obj);
		$(placeholder).prepend(tabMeta);
		$(placeholder).tabs();
	}
}).implement(PluginInterface);
GetAnnouncementPlugin = Class.extend({
	init: function()	{
		this.name = "GetAnnouncementPlugin";
	},
	
	onBegin: function()	{
		this.onGetAnnouncement();
		this.startInterval(300*1000, this.onGetAnnouncement);
	},

	onGetAnnouncement: function()	{
		var obj = this;
		this.onAjax('ajax', 'get-announcement', {}, 'GET', {
			'onSuccess': function(ret)	{
				if (ret == undefined || ret == "")
					return;
				//find if plugin already loaded
				var containerHTML = tmpl('GetAnnouncementPluginContainer', {});
				if ($('div#GetAnnouncementPlugin').length <= 0)	{
					$('div.extension-point[extensionName="PostTop"]:first').prepend(containerHTML);
				}
				$('div#GetAnnouncementPlugin').html(ret);
				$('div#GetAnnouncementPlugin').fadeOut(60000);
			}
		});
	},
	
	onEnd: function()	{
		this.stopInterval();
	}
}).implement(PluginInterface).implement(IntervalTimerInterface).implement(AjaxInterface);

GlobalNotificationPlugin = Class.extend({
	init: function()	{
		this.name = "GlobalNotificationPlugin";
	},
	
	onCloseGlobalNotify: function()	{
		$('div#NotifyGlobalPlugin').stop().animate({opacity: '100'}).hide();
	},
	
	onNotifyGlobal: function(eventData)	{
		var containerHTML = tmpl('NotifyGlobalPluginContainer', {});
		if ($('div#NotifyGlobalPlugin').length <= 0)	{
			$('div.extension-point[extensionName="PostTop"]:first').prepend(containerHTML);
		}
		$('div#NotifyGlobalPlugin').find('span.notifyContent').html(eventData);
		$('div#NotifyGlobalPlugin').stop().animate({opacity: '100'});
		$('div#NotifyGlobalPlugin').show().fadeOut(30000);
	}
}).implement(PluginInterface).implement(IntervalTimerInterface).implement(AjaxInterface);

KeepAlivePlugin = Class.extend({
	init: function()	{
		this.name = "KeepAlivePlugin";
	},
	
	onBegin: function()	{
		this.onKeepAlive();
		this.startInterval(15*60*1000, this.onKeepAlive);
	},

	onKeepAlive: function()	{
		this.onAjax('ajax', 'index', {}, 'GET', {
			'onSuccess': function(ret)	{
				
			}
		});
	},
	
	onEnd: function()	{
		this.stopInterval();
	}
}).implement(PluginInterface).implement(IntervalTimerInterface).implement(AjaxInterface);
/**
 * 
 */

ProfileImageCheckPlugin = Class.extend({
	init: function()	{
		this.name = "ProfileImageCheckPlugin";
	},
	
	onHtmlRendered: function(eventData)	{
		this.render();
	},
	
	onHtmlUpdated: function(eventData)	{
		this.render();
	},
	
	onFixBrokenImage: function(eventData){
		this.render();
	},
	
	render: function(eventData)	{
		$('.extension-point[extensionName="ProfileImageCheck"]').each(function(index, value)	{
			$(value).find(".bkp_pic_profile img").error(
				function() {
					$(this).attr("src", "styles/images/unknown.png");
				});
		});
	},
	
	onRequestProfileImageCheck: function(eventData){
		var zone = eventData.zone;
		$(zone).find(".bkp_pic_profile img").error(
			function() {
				$(this).attr("src", "styles/images/unknown.png");
		});
	}
}).implement(PluginInterface);

/**
 * 
 */

NavigateRoutePlugin = Class.extend({
	init: function()	{
		this.name = "NavigateRoute";
	},
	
	onGoToPrevious: function(eventData)	{
		//console.log("Go to previous page");
		history.go(-2);
	},
	
	onGoToHome: function(eventData)	{
		//console.log("Go to homepage");
		var subject = SingletonFactory.getInstance(Subject);
		var request = new Request("Home",undefined, null); 
		subject.notifyEvent('RequestRoute', request);
	},
	
	onGoToPage: function(eventData)	{
		var subject = SingletonFactory.getInstance(Subject);
		var request ;
		if(eventData.page == undefined){
			//console.error("Error ! No page to go to");
		}else{
			var pagename = eventData.page;
			var params = eventData.params;
			request = new Request(pagename, undefined, params);
			subject.notifyEvent('RequestRoute', request);
		}
	}
}).implement(PluginInterface);

NavigatorPlugin = Class.extend({
	init: function() {
		this.name = "NavigatorUI";
		this.pageLinks = Array();
		this.numPages = null;
		this.numDocs = null;
		this.rows = 10;
		this.curPage = 0;
		this.searchPage = 0;
		this.dataLength = 0;
		this.searchController = "";
	},
	
	onFetchSearchResultNumber: function(eventData){
		var objParam = {};
		objParam.numDocs = eventData.numDocs || 0;
		var template = tmpl("SearchResultDynamicPortlet-SearchResultNumber",objParam);
		//console.log("FetchSearchResultNumber dasfa");
		$('.extension-point[extensionName="SearchResultHeader"]').each(function(index, value)	{
			//console.log("onFetchSearchResultNumber")
			$(value).append(template);
		});
	},
	
	onFetchNavigationLink: function(eventData){
		this.numDocs = eventData.numDocs;
		this.rows = eventData.rows;
		this.searchPage = eventData.searchPage;
		this.dataLength = eventData.dataLength;
		this.query = eventData.query;
		this.core = eventData.core;
		this.searchController = eventData.searchController;
		
		var currentPlugin = this;
		$('.extension-point[extensionName="NavigatorUI"]').each(function(index, value)	{
			$(value).append(currentPlugin.fetchPageLink());
		});
	},
	
	fetchPageLink: function(){
		var result = $("<div></div>");
		if(this.dataLength == 0){
			return result;
		}
		var numPages = Math.ceil(this.numDocs / this.rows);
		if(numPages == 0){
			numPages = 1;
		}
		var curPage = parseInt(this.searchPage); 
		var pageLinks = Array();
		if (curPage > numPages){
			curPage = numPages;
		}
		if (curPage <= 0){
			curPage = 1;
		}
		
		for(var x = 1; x <= numPages; x ++) {
			if (x == curPage) {
				var objParam = {};
				objParam.content = x;
				pageLinks[x-1] = tmpl("CommonPortlet-NavCurrent",objParam);
			} else {
				var objParam = {};
				objParam.query = this.query;
				objParam.core = this.core;
				objParam.searchPage = x;
				objParam.content = x;
				objParam.rows = this.rows;
				objParam.searchController = this.searchController;//"SearchResultDynamic";
				pageLinks[x-1] = tmpl("CommonPortlet-NavOther",objParam);
			}
		}
		
		if (curPage > 1 && curPage <= pageLinks.length){
			var objParam = {};
			objParam.query = this.query;
			objParam.core = this.core;
			objParam.searchPage = curPage-1;
			objParam.content = "&#171 Trước&nbsp;";
			objParam.rows = this.rows;
			objParam.searchController = this.searchController;//"SearchResultDynamic"
			result.append(tmpl("CommonPortlet-NavOther",objParam));
		}
		
		
		for (var key= curPage-11; key <= curPage+9; key++ ) {
			if (key<0) continue;
			if (key>= pageLinks.length) continue;
			if (key == curPage)
				result.append(pageLinks[key]);
			else
				result.append(pageLinks[key]);
		}		
		
		if(curPage < pageLinks.length){
			var objParam = {};
			objParam.query = this.query;
			objParam.core = this.core;
			objParam.searchPage = curPage+1;
			objParam.content = "&nbsp;Sau&nbsp;&#187";
			objParam.rows = this.rows;
			objParam.searchController = this.searchController;;//"SearchResultDynamic";
			result.append(tmpl("CommonPortlet-NavOther",objParam));
		}
		return result;
	}
}).implement(PluginInterface);

/**
 * 
 */

BKPTextEditorPlugin = Class.extend({
	init : function() {
		this.name = "BKPTextEditor";
		this.mceNeeded = false;
		this.config = eval("(" + tmpl("AnswerPortlet-MCEConfig", {}) + ")");
	},

	onEditorCreateInstance : function(eventData) {
		var id = eventData.id;
		document.contentEditable = "true";
		document.designMode = "on";
		// console.log("destroy on instance " + id);
		tinymce.execCommand('mceRemoveControl', true, id);
		// console.log("done destroying");

		// console.log("Create MCE Instance ON " + id);
		tinymce.init(this.config);
		tinymce.execCommand('mceAddControl', true, id);
		try {
			tinymce.execCommand("mceFocus", false, id);
		} catch (e) {
			var editor = tinymce.getInstanceById(id);
			if (editor) {
				editor.execCommand('mceStartTyping');
				editor.contentWindow.focus();
			}
		}
		// console.log("Done creating MCE");
		document.contentEditable = "false";
		document.designMode = "off";
	},
	
	onTinyEditorInit: function(eventData){
		var id = eventData.id;
		var content = eventData.content;
		var mem = SingletonFactory.getInstance(Application).getSystemProperties().get("memcached.tinyeditor");
		if(mem == undefined){
			mem = Array();
		}
		if(mem[id] != undefined){
			return;
		}
		var instance = new TINY.editor.edit('editor' ,{
		    id:id,
		    height:'200px',
		    width:'100%',
		    cssclass:'te',
		    controlclass:'tecontrol',
		    rowclass:'teheader',
		    dividerclass:'tedivider',
		    controls:['bold','italic','underline','|',
		              'orderedlist','unorderedlist','|','outdent','indent','|','leftalign',
		              'centeralign','rightalign','blockjustify','|','image'],
		    fonts:['Verdana','Arial','Georgia','Trebuchet MS'],
		    xhtml:true,
		    cssfile:'static/js/thirdparty/tinyeditor/style.css',
		    bodyid:'editor',
		    footerclass:'tefooter',
		    toggle:{text:'source',activetext:'wysiwyg',cssclass:'toggle'},
		    resize:{cssclass:'resize'}
		});
		mem[id]= instance;
		SingletonFactory.getInstance(Application).getSystemProperties().set("memcached.tinyeditor",mem);
	},
	
	onEnd: function(){
		SingletonFactory.getInstance(Application).getSystemProperties().set("memcached.tinyeditor",undefined);
	},

	myExecCommand : function(aCommandName, aShowDefaultUI, aValueArgument) {
		document.contentEditable = true;
		document.execCommand(aCommandName, aShowDefaultUI, aValueArgument);
		document.contentEditable = false;
	}

}).implement(PluginInterface);

/**
 * 
 */

PostPlugin = Class
		.extend(
				{
					init : function() {
						this.name = "PostPlugin";
						this.app = SingletonFactory.getInstance(Application);
						this.root = this.app.getSystemProperties().get(
								"host.root");
						this.topics = this.app.getSystemProperties().get(
								"memcached.topics");
						this.contexts = this.app.getSystemProperties().get(
								"memcached.contexts");
						this.contextsDescription = null;

						this.addedContexts = null;
						this.contextMap = Array();
						this.addedContextsNumber = 0;
						this.addedTopics = null;
						this.topicMap = Array();
						this.topicAvaiContextCommit = Array();
						this.topicNewContextCommit = Array();
					},

					onVoteUpQuestion : function(eventData) {
						this.checkUserLogin(eventData, "VoteUpQuestion");
					},

					voteUpQuestion : function(eventData) {
						var url = this.prepareQuestionUrl(eventData, 1);
						$.get(url, {}, function(ret) {
							ret = $.parseJSON(ret);
							ret = ret.result;
							if (ret == "success") {
								var up = parseInt($(".bkp_q_vote_up").html());
								up += 1;
								$(".bkp_q_vote_up").html(up);
								return;
							}
						});
					},

					onVoteDownQuestion : function(eventData) {
						this.checkUserLogin(eventData, "VoteDownQuestion");
					},

					voteDownQuestion : function(eventData) {
						var url = this.prepareQuestionUrl(eventData, 0);
						$.get(url, {}, function(ret) {
							ret = $.parseJSON(ret);
							ret = ret.result;
							if (ret == "success") {
								var up = parseInt($(".bkp_q_vote_down").html());
								up += 1;
								$(".bkp_q_vote_down").html(up);
								return;
							}
						});
					},

					// login
					onVoteAnswerIncrease : function(eventData) {
						this.checkUserLogin(eventData, "VoteAnswerIncrease");
					},

					voteAnswerIncrease : function(eventData) {
						var url = this.prepareUrl(eventData, 1);
						// console.log("URL:" + url)
						$.get(url, {}, function(ret) {
							ret = $.parseJSON(ret);
							ret = ret.result;
							if (ret == "success") {
								var aid = eventData.aid;
								var current = parseInt($(
										"#answer-" + aid + "-voteNum")
										.children().html());
								current += 1;
								$("#answer-" + aid + "-voteNum").children()
										.html(current);
								// $("#vote-up-" + aid).attr("onclick", "return
								// false");
								return;
							}
						});
					},

					// login
					onVoteAnswerDecrease : function(eventData) {
						this.checkUserLogin(eventData, "VoteAnswerDecrease");
					},

					voteAnswerDecrease : function(eventData) {
						var url = this.prepareUrl(eventData, 0);
						$.get(url, {}, function(ret) {
							ret = $.parseJSON(ret);
							ret = ret.result;
							if (ret == "success") {
								var aid = eventData.aid;
								var current = parseInt($(
										"#answer-" + aid + "-voteNum")
										.children().html());
								current -= 1;
								$("#answer-" + aid + "-voteNum").children()
										.html(current);
								// $("#vote-down-" + aid).attr("onclick",
								// "return false");
								return;
							}
						});
					},

					prepareUrl : function(eventData, type) {
						// FIXME: UID!!!!
						var uid = SingletonFactory.getInstance(Application)
								.getSystemProperties().get("user.id");
						var aid = eventData.aid;
						var root = SingletonFactory.getInstance(Application)
								.getSystemProperties().get("host.root");
						var url = root + "answer/update-vote/uid/" + uid
								+ "/aid/" + aid + "/type/" + type;
						return url;
					},

					prepareQuestionUrl : function(eventData, type) {
						var qid = eventData.id;
						var root = SingletonFactory.getInstance(Application)
								.getSystemProperties().get("host.root");
						var url = root + "question/update-vote/qid/"
								+ qid + "/type/" + type;
						return url;
					},

					onToggleDownEditTopic : function(eventData) {
						var id = eventData.id;
						$("#" + id).slideToggle('fast');
						$("#bkp-topic-search-new").val("");
						this.buildTopics(SingletonFactory.getInstance(
								Application).getSystemProperties().get(
								"memcached.topics"));
					},

					onToggleUpEditTopic : function(eventData) {
						var id = eventData.id;
						// $("#" + id).children("input[type=text]").val("");
						$("#" + id).slideToggle('fast');
					},

					// login
					onTopicAdded : function(eventData) {
						this.checkUserLogin(eventData, "TopicAdded");
					},

					topicAdded : function(eventData) {
						var id = eventData.id;
						// var value = $("#" +
						// id).children("input[type=text]").val().trim();
						// if(value == ""){
						// return;
						// }
						var params = SingletonFactory.getInstance(Page)
								.getRequest().getParams();
						var questionID = params["qid"];
						var selected = $("#" + id + "  option:selected");
						for ( var i = 0; i < selected.length; i++) {
							var value = $(selected[i]).val();
							var text = $(selected[i]).text();

							// TODO: đưa value lên server
							// đưa value vào trong list
							// Nếu trong list có rồi thì thoi
							var topicAdded = this.app.getSystemProperties()
									.get("memcached.addedTopics");
							if (topicAdded[value] != undefined) {
								return;
							}

							var objParam = {};
							objParam.tid = generateId("tt");
							objParam.content = text;
							objParam.cid = value;
							objParam.uid = this.app.getSystemProperties().get("user.id");
							var newTp = tmpl("AnswerPortlet-Topic", objParam);
							
							$("#" + id).parent().parent().siblings(
									".bkp_question_topics").append(newTp);

							// set back to memcached
							topicAdded[value] = objParam.tid;
							var sysProp = this.app.getSystemProperties();
							sysProp.set("memcached.addedTopics", topicAdded);

							// dump to server
							var curUrl = this.root
									+ "question/add-catchword/qid/"
									+ questionID + "/cid/" + value;
							var sbj = SingletonFactory.getInstance(Subject);
							$.ajax({
								url : curUrl,
								data : {},
								success : function(ret) {
									// console.log("Cập nhật thành công");
									sbj.notifyEvent("NotifyGlobal",
											"Thêm thành công");
								},
								error : function() {
									// console.log("Cập nhật thất bại");
									sbj.notifyEvent("NotifyGlobal",
											"Thêm thất bại");
								}
							});
						}
					},

					onTopicDeleted : function(eventData) {
						this.checkUserLogin(eventData, "TopicDeleted");
					},

					topicDeleted : function(eventData) {
						var id = eventData.id;
						var params = SingletonFactory.getInstance(Page)
								.getRequest().getParams();
						var questionID = params["qid"];
						var value = $("#" + id).attr("cid")
						var text = $("#" + id + " label").text();

						var topicAdded = this.app.getSystemProperties().get(
								"memcached.addedTopics");
						topicAdded[value] = undefined;
						var sysProp = this.app.getSystemProperties();
						sysProp.set("memcached.addedTopics", topicAdded);

						$("#" + id).remove();
						// dump to server
						var curUrl = this.root
								+ "question/remove-catchword/qid/" + questionID
								+ "/cid/" + value;
						var sbj = SingletonFactory.getInstance(Subject);
						$
								.ajax({
									url : curUrl,
									data : {},
									success : function(ret) {
										sbj.notifyEvent("NotifyGlobal",
												"Xóa thành công");
									},
									error : function() {
										sbj.notifyEvent("NotifyGlobal",
												"Xóa thất bại");
									}
								});
					},

					onTopicChanged : function(eventData) {
						var id = eventData.id;
						var pid = eventData.pid;
						var value = $("#" + id).val().trim().replace("  ", " ")
								.toLowerCase();
						var e = eventData.e;
						var topics = SingletonFactory.getInstance(Application)
								.getSystemProperties().get("memcached.topics");
						var arr = Array();
						var newTopics = null;
						var isEqual = false;
						for ( var key in topics) {
							var curObj = topics[key];
							var content = curObj['catchWord'].toLowerCase();
							var match = new RegExp(value);
							if (content == value) {
								isEqual = true;
							}
							if (match.test(content)) {
								arr.push(curObj);
							}
						}

						newTopics = this.buildTopics(arr);
						if (newTopics != null) {
							$("#" + pid).empty().append(newTopics.children());
						}
					},

					buildTopics : function(arr) {
						var result = $("<div><div></div></div>");
						for ( var key in arr) {
							var curObj = arr[key];
							var newTp = $("<option value='" + curObj['id']
									+ "'>" + curObj['catchWord'] + "</option>");
							result.children().append(newTp);
						}
						return result.children();
					},

					onMoreContent : function(eventData) {
						var uiid = eventData.uiid;
						var parentID = eventData.pid;
						var templateID = eventData.tid;
						var templateFields = eventData.fields;
						var id = SingletonFactory.getInstance(Page)
								.getRequest().getParams()['qid'];
						var name = eventData.name;
						var type = eventData.type;
						var action = eventData.action;
						var page = parseInt($("#" + uiid).attr("page"));
						var rows = eventData.rows;
						var curPlg = this;
						var curUrl = this.root + type + "/" + action + "/"
								+ name + "/" + id + "/page/" + page + "/rows/"
								+ rows;
						var result = null;
						var sbj = SingletonFactory.getInstance(Subject);
						$.ajax({
							url : curUrl,
							async : false,
							success : function(ret) {
								ret = $.parseJSON(ret);
								ret = ret.result;
								if (ret == undefined || ret == "error") {
									sbj.notifyEvent("NotifyGlobal",
											"Không lấy thêm được!");
									return;
								}
								result = ret;
							}
						});

						var resultUI = $("<div></div>");
						// shit
						result = result.answers;

						var count = 0;
						for ( var key in result) {
							var curObj = result[key];
							count++;
							var objParam = {};
							for ( var field in templateFields) {
								var fName = templateFields[field];
								var fArr = Array();
								if (fName.indexOf(".") != -1) {
									fArr = fName.split(".");
									objParam[field] = curObj[fArr[0]][fArr[1]]
											|| "";
								} else {
									objParam[field] = curObj[fName] || "";
								}

							}
							resultUI.append(tmpl(templateID, objParam));
						}
						resultUI.children().children().hide();
						$("#" + parentID)
								.append(resultUI.children().children());

						// Presenting only
						var numChild = $("#" + parentID).children().length;
						var from = numChild - count;
						$("#" + parentID).children().slice(from, numChild)
								.slideToggle("fast");

						var sum = page + count;
						$("#" + uiid).attr("page", sum);

						var sbj = SingletonFactory.getInstance(Subject);
						sbj.notifyEvent("FixBrokenImage");
						sbj.notifyEvent("BindingChangeAnswer");
						sbj.notifyEvent("ShowBio", {'qid': id});
						sbj.notifyEvent("RenderBioEditLink", {'qid': id});
					},

					onSubmitAnswer : function(eventData) {
						this.checkUserLogin(eventData, "SubmitAnswer");
					},

					submitAnswer : function(eventData) {
						var request = SingletonFactory.getInstance(Page)
								.getRequest();
						var params = request.getParams();
						var qid = params['qid'];
						if (qid == undefined) {
							return;
						}
						var sbj = SingletonFactory.getInstance(Application)
								.getSystemProperties().get(
										"memcached.answeredID");
						var userid = SingletonFactory.getInstance(Application)
								.getSystemProperties().get("user.id");
						if (sbj != undefined && userid != undefined) {
							for ( var key in sbj) {
								var curID = sbj[key];
								if (curID == userid) {
									alert("Mỗi câu hỏi chỉ được một câu trả lời. Bạn chỉ có thể được chỉnh sửa");
									return;
								}
							}
						}
						var pid = eventData.pid;
						var sbj = SingletonFactory.getInstance(Subject);
						sbj.notifyEvent("AjaxLoading", {
							id : pid
						});

						var mceID = eventData.id;
						var uid = eventData.uid;
						// var content = tinyMCE.get(mceID).getContent();
						var instance = SingletonFactory
								.getInstance(Application).getSystemProperties()
								.get("memcached.tinyeditor");
						var content = instance[mceID].e.body.innerHTML;
						// var content = $("#editor-"+id).html();
						var curUrl = this.root + "answer/add";
						$
								.ajax({
									url : curUrl,
									data : {
										questionID : qid,
										userID : uid,
										content : content
									},
									success : function(ret) {
										ret = $.parseJSON(ret);
										var result = ret.result;
										sbj.notifyEvent("AjaxComplete", {
											id : pid,
											msg : ret.message
										});
										if (result == "error") {
											setTimeout(function() {
												$("#" + pid).children().show();
											}, 3000);
										} else {
											// tinyMCE.get(mceID).setContent("");
											instance[mceID].e.body.innerHTML = "";
										}
									},
									error : function(ret) {
										sbj
												.notifyEvent(
														"AjaxComplete",
														{
															id : pid,
															msg : "Không thể kết nối tới máy chủ. Mong bạn thử lại sau!"
														});
										setTimeout(function() {
											$("#" + pid).children().show();
										}, 3000);
									}
								});
					},

					onCreateNewTopicContext : function(eventData) {
						this.checkUserLogin(eventData, "CreateNewContext");
					},

					buildLocalAnswer : function() {
					},

					onAjaxLoading : function(eventData) {
						var id = eventData.id;
						$("#" + id).children().hide();
						var img = $("<div id='ajax-div-"
								+ id
								+ "' class='bkp_ajax_wrapper'><center><img src='static/images/ajax-loader-1.gif' height='50px' width='50px'></center></div>");
						$("#" + id).append(img);
					},

					onAjaxComplete : function(eventData) {
						var id = eventData.id;
						var msg = eventData.msg;
						$("#" + id).children("#ajax-div-" + id).remove();
						var tmpID = "ajax-msg-" + id;
						$("#" + id)
								.append(
										"<div id='"
												+ tmpID
												+ "' class='bkp_ajax_wrapper'><center><p  class='bkp_ajax_msg'>"
												+ msg + "</p></center></div>");

						setTimeout(function() {
							$('#' + tmpID).fadeOut('fast');
							$("#" + id).children("#" + tmpID).remove();
						}, 3000);
					},

					onBindingChangeAnswer : function() {
						var uid = SingletonFactory.getInstance(Application)
								.getSystemProperties().get("user.id");
						var currentPlt = this;
						$(".extension-point[extensionName='AnswerExtension']")
								.each(
										function() {
											var curUid = $(this).attr("uid");
											var curAid = $(this).attr("aid");
											var flag = $(this).attr("flag") || false;
											// TODO: Fix 1 HERE
											if (curUid == uid && !flag) {
												$(this).attr("flag", "true");
												$(this)
														.append(
																$("<a onclick=\"generateEvent(&apos;ShowMCE&apos;,{uid:&apos;"
																		+ curUid
																		+ "&apos;,aid:&apos;"
																		+ curAid
																		+ "&apos;})\">Sửa</a>"));
												var objParam = {};
												objParam.uid = curUid;
												objParam.aid = curAid;
												$(
														"#extension-content-plhld-"
																+ curAid + "-"
																+ curUid)
														.append(
																tmpl(
																		"AnswerPortlet-TextArea",
																		objParam));
												var curID = "editor_" + curAid
														+ "_" + curUid;
												var content = $(
														"#answer-content-"
																+ curAid)
														.html();
												$("#" + curID).val(content);
												var sbj = SingletonFactory
														.getInstance(Subject);
												// sbj.notifyEvent("TinyEditorInit",{id:curID,
												// content:content});
												// sbj.notifyEvent("EditorCreateInstance",{id:curID,
												// content:content});
												
												$(this).append(" • ");
											} 
											
											if(!flag){
												$(this).attr("flag", "true");
												$(this).append($("<a onclick=\"generateEvent(&apos;AddComment&apos;,{uid:&apos;"
														+ curUid
														+ "&apos;,aid:&apos;"
														+ curAid
														+ "&apos;})\">Thêm Comment</a>"));
												
												$(this).append(" • ");
																							
												$(this).append("<a onclick=\"generateEvent(&apos;ShowComment&apos;,{uid:&apos;"
														+ curUid
														+ "&apos;,aid:&apos;"
														+ curAid
														+ "&apos;})\">"+'<span class="statcom"><span class="statcom_header" id="comment_no_'+ curAid + "_" + curUid+'" style="font-size:10px; font-weight:normal; background: transparent;">0</span><span> Comment</span></span></a>');
												
												// fetch data
												var paramCmtNo = {};
												paramCmtNo.uid = curUid;
												paramCmtNo.aid = curAid;
												currentPlt.getCommentNumber(paramCmtNo);
												
												// add comment list placeholder
												var plhldID = "extension-content-plhld-" + curAid + "-" + curUid;
												var element = $("#"+plhldID + " #comment-list-plhld-" + curAid + "-" + curUid);
												if(element.length == 0){
													var objParam = {};
													objParam.aid = curAid;
													objParam.uid = curUid;
													$("#" + plhldID).append($(tmpl("CommonPortlet-CommentList", objParam)));
												}
												
												// add comment add new placeholder
												element = $("#" + plhldID + " #comment-addnew-plhld-" + curAid + "-" + curUid );
												if(element.length == 0){
													var objParam = {};
													objParam.aid = curAid;
													objParam.uid = curUid;
													objParam.curuid = uid || -1;
													$("#" + plhldID).append($(tmpl("CommonPortlet-AddNewComment", objParam)));
												}
											}
											
										});
					},
					
					getCommentNumber: function(eventData){
						var curUid = eventData.uid;
						var curAid = eventData.aid;
						//getNoCommentAction
						var url = this.root + "answer/get-no-comment";
						$.get(url, {aid: curAid}, function(ret){
							try {
								ret = $.parseJSON(ret);
								if(ret.result == 'error'){
									return;
								}
								$("#comment_no_"+ curAid + "_" + curUid).html(ret.data);
							} catch (e) {
								// TODO: handle exception
							}
						});
					},

					onShowMCE : function(eventData) {
						var curUid = eventData.uid;
						var curAid = eventData.aid;
						var curID = "editor_" + curAid + "_" + curUid;
						var content = $("#answer-content-" + curAid).html();
						$("#" + curID).val(content);

						var sbj = SingletonFactory.getInstance(Subject);
						sbj.notifyEvent("TinyEditorInit", {
							id : curID,
							content : ""
						});
						// sbj.notifyEvent("EditorCreateInstance",{id:curID,
						// content:content});
						var answerPlhldID = "answer-editor-" + curAid + "-" + curUid + "";
						$("#extension-content-plhld-" + curAid + "-" + curUid)
								.children("div[id='"+answerPlhldID+"']").show('fast');
					},

					onAcceptChanges : function(eventData) {
						this.checkUserLogin(eventData, "AcceptChanges");
					},

					acceptChanges : function(eventData) {
						var curUid = eventData.uid;
						var curAid = eventData.aid;
						var mceID = "editor_" + curAid + "_" + curUid;
						var instance = SingletonFactory
								.getInstance(Application).getSystemProperties()
								.get("memcached.tinyeditor");
						var content = instance[mceID].e.body.innerHTML;
						// var content = tinymce.get(mceID).getContent();
						content = this.checkImage(content);

						var curUrl = this.root + "answer/update/uid/" + curUid
								+ "/aid/" + curAid;
						var sbj = SingletonFactory.getInstance(Subject);
						$
								.ajax({
									url : curUrl,
									type : "POST",
									data : {
										"content" : content
									},
									success : function(ret) {
										$("#answer-content-" + curAid).html(
												content);
										sbj.notifyEvent("NotifyGlobal",
												"Sửa thành công");
									},
									error : function(ret) {
										// console.log("Change answer
										// unsuccessfully");
										sbj.notifyEvent("NotifyGlobal",
												"Sửa thất bại");
									}
								});

						$("#extension-content-plhld-" + curAid + "-" + curUid)
								.children().hide('fast');
					},
					
					checkImage: function(html){
						var parent = $("<div></div>");
						$(parent).append(html);
						var tmp = $(parent).find("img").each(function(index,value){
							var imgSrc = $(value).attr("src");
							
							var newImg = new Image();
							newImg.src = imgSrc;
							var height = newImg.height;
							var width = newImg.width;
							if(height == 0 || width == 0 || imgSrc == ""){
								$(value).remove();
							}
							if(width >= 400){
								$(value).attr('width','400');
							}
							$(value).css("vertical-align","middle");
							$(value).css("display","block");
							var subTmp = $("<center></center>");
							var valueTmp = $(value).clone();
							$(value).replaceWith($(subTmp).append($(valueTmp)));
						});
						return $(parent).html();
					},

					checkUserLogin : function(eventData, type) {
						var evtArgs = {};
						evtArgs.type = type;
						evtArgs.evtData = eventData;
						var sbj = SingletonFactory.getInstance(Subject);
						sbj.notifyEvent("NeedLogin", evtArgs);
					},

					onRejectChanges : function(eventData) {
						var curUid = eventData.uid;
						var curAid = eventData.aid;
						$("#extension-content-plhld-" + curAid + "-" + curUid)
								.children("div[id='answer-editor-"+ curAid +"-"+curUid + "']").hide('fast');
					},

					onLoginSuccess : function(eventData) {
						var type = eventData.type;
						var evtArgs = eventData.evtData;
						if (type != undefined && evtArgs != undefined) {
							switch (type) {
							case "VoteAnswerIncrease":
								this.voteAnswerIncrease(evtArgs);
								break;
							case "VoteAnswerDecrease":
								this.voteAnswerDecrease(evtArgs);
								break;
							case "TopicAdded":
								this.topicAdded(evtArgs);
								break;
							case "TopicDeleted":
								this.topicDeleted(evtArgs);
								break;
							case "SubmitAnswer":
								this.submitAnswer(evtArgs);
								break;
							case "AcceptChanges":
								this.acceptChanges(evtArgs);
								break;
							case "CreateNewContext":
								this.createNewContextSuccess(evtArgs);
								break;
							case "VoteUpQuestion":
								this.voteUpQuestion(evtArgs);
								break;
							case "VoteDownQuestion":
								this.voteDownQuestion(evtArgs);
								break;
							default:
								break;
							}
						}
						this.onCheckTopicEditable();
					},

					createNewContextSuccess : function() {
						var subject = SingletonFactory.getInstance(Subject);
						var rq = SingletonFactory.getInstance(Page)
								.getRequest();
						var params = rq.getParams();
						var request = new Request("TopicCreatePage", "", {
							"pageCallBack" : "Question",
							"needParam" : true,
							"paramName" : "qid",
							"paramVal" : params['qid']
						});
						subject.notifyEvent('RequestRoute', request);
					},
					
					onCheckTopicEditable: function(eventData){
						var currentUid = SingletonFactory.getInstance(Application).getSystemProperties().get("user.id");
						$(".extension-point[extensionName='CheckTopicEditable']").each(function(index,value){
							 var uid = $(value).attr("uid");
							 if(uid == currentUid){
								$(value).find(".delToken").show(); 	
							 } else {
							 	$(value).find(".delToken").hide();
							 }
						});
					},
					
					onCheckTopicEditableZone: function(eventData){
						var zone = eventData.zone;
						var currentUid = SingletonFactory.getInstance(Application).getSystemProperties().get("user.id");
						$(zone).find(".extension-point[extensionName='CheckTopicEditable']").each(function(index,value){
							 var uid = $(value).attr("uid");
							 if(uid == currentUid){
								$(value).find(".delToken").show(); 	
							 } else {
							 	$(value).find(".delToken").hide();
							 }
						});
					},

					onHtmlUpdated : function() {
						var id = SingletonFactory.getInstance(Application)
								.getSystemProperties().get("user.id");
						$(
								".extension-point[extensionName='ProfileImageCheck'][uid='"
										+ id + "']").css("background-color",
								"#FAFAFA");
					}

				}).implement(PluginInterface);

/**
 * 
 */

CommentPlugin = Class
		.extend(
				{
					init : function() {
						this.name = "CommentPlugin";
						this.app = SingletonFactory.getInstance(Application);
						this.root = this.app.getSystemProperties().get(
								"host.root");
					},

					onShowComment: function(eventData){
						var uid = eventData.uid;
						var aid = eventData.aid;
						var plhldID = "#extension-content-plhld-" + aid + "-" + uid ;
						var commentAnswerPlhldID = "#comment-list-plhld-" + aid + "-" + uid ; 
						var element = $(plhldID + " " + commentAnswerPlhldID);
						var currentPlt = this;
						
						if($(element).attr("flag") == undefined || $(element).attr("flag") == false){
							$(element).attr("flag",true);
						} else {
							$(element).removeAttr("flag");
							$(commentAnswerPlhldID).slideToggle();
							return;
						}
						
						//ajax loading
						//getAllCommentsAction
						var url = this.root + "answer/get-all-comments/";
						var sbj = SingletonFactory.getInstance(Subject);
						// xoay xoay ajax => nen de thanh plugin
						
						$.get(url, {aid:aid}, function(ret){
							try {
								ret = $.parseJSON(ret);								
								if(ret.result == "error"){
									//error
									return;
								}
								$(commentAnswerPlhldID).hide();
								$(commentAnswerPlhldID).empty();

								//fetch comment number
								currentPlt.bindNumberOfComment(aid,uid,ret.data.length);
								
								// dump to list
								ret = ret.data;
								for(var key in ret){
									var objParam = {};
									objParam.content = ret[key]["content"];
									objParam.date = formatDate(ret[key]["created_date"]);
									objParam.uid = ret[key]["userID"];
									objParam.username = ret[key]["name"] ;
									objParam.avatar = ret[key]["avatar"];
									var template = $(tmpl("CommonPortlet-CommentItem",objParam));
									$(commentAnswerPlhldID).append(template);
								}
								var checkImg = {};
								checkImg.zone = $(commentAnswerPlhldID);
								sbj.notifyEvent("RequestProfileImageCheck", checkImg);
								$(commentAnswerPlhldID).slideToggle("slow");
							} catch (e) {
								// error
							}
						});
					},
					
					bindNumberOfComment: function(aid, uid, data){
						var cmtID = "comment_no_"+aid+"_"+uid;
						$("#" + cmtID).html(data);
					},
					
					onAddComment: function(eventData){
//						$.facebox("Chức năng này đang được hoàn thiện. Mong bạn vui lòng quay lại sau.");
						var uid = eventData.uid;
						var aid = eventData.aid;
						var plhldID = "#extension-content-plhld-" + aid + "-" + uid ;
						var commentAnswerPlhldID = " #comment-addnew-plhld-" + aid + "-" + uid ; 
						var element = $(plhldID + " " + commentAnswerPlhldID);
						$(element).slideToggle('fast');
					},
					
					onAddNewComment: function(eventData){
						this.checkUserLogin(eventData, "AddNewComment");
					},
					
					addNewComment: function(eventData){
						var plhldContent = eventData.id;
						var aid = eventData.aid;
						var uid = eventData.uid;
						var content = $("#"+plhldContent).val();
						var currentPlt = this;
						if(jQuery.trim( content ) == ""){
							$.facebox("Bạn chưa nhập thông tin!");
							return;
						}
						var url = this.root + "answer/add-new-comment/";
						var sbj = SingletonFactory.getInstance(Subject);
						var commentAnswerPlhldID = " #comment-addnew-plhld-" + aid + "-" + uid ;
						// xoay xoay ajax => nen de thanh plugin
						
						$.post(url, {aid:aid, content:content}, function(ret){
							try {
								ret = $.parseJSON(ret);
								ret = ret.result;
								if(ret == "error"){
									//error
									return;
								}
								sbj.notifyEvent("NotifyGlobal",
								"Thêm thành công");
								$(commentAnswerPlhldID).slideToggle("fast");
								
								// bind number of data
								var cmtID = "comment_no_"+aid+"_"+uid;
								var cmtNo = eval($("#"+cmtID).html());
								cmtNo = cmtNo + 1;
								currentPlt.bindNumberOfComment(aid,uid,cmtNo);
								$("#"+plhldContent).val("");
							} catch (e) {
								// error
							}
						});
					},
					
					checkUserLogin : function(eventData, type) {
						var evtArgs = {};
						evtArgs.type = type;
						evtArgs.evtData = eventData;
						var sbj = SingletonFactory.getInstance(Subject);
						sbj.notifyEvent("NeedLogin", evtArgs);
					},
					
					onLoginSuccess : function(eventData) {
						var type = eventData.type;
						var evtArgs = eventData.evtData;
						if (type != undefined && evtArgs != undefined) {
							switch (type) {
							case "AddNewComment":
								this.addNewComment(evtArgs);
								break;
							default:
								break;
							}
						}
					}
				}).implement(PluginInterface);

/**
 * 
 */

EditPendingQuestionsPlugin = Class
		.extend(
				{
					init : function() {
						this.name = "EditPendingQuestionsPlugin";
						this.app = SingletonFactory.getInstance(Application);
						this.root = this.app.getSystemProperties().get(
								"host.root");
						this.topics = this.app.getSystemProperties().get(
								"memcached.topics");
						this.addedTopics = null;
						this.pendingQuestion = {};
					},

					// From AnswerPortlet
					getAjaxAllTopics: function(){
						var curPlt = this;
						var curUrl = this.root + "catchword/get-all-catchwords/";
						$.ajax({url:curUrl, async:false , success: function(ret){
							ret = $.parseJSON(ret);
							ret = ret.result;
							if(ret == undefined || ret == "error"){
								//console.log("Cannot get all topic")
								return;
							}
							curPlt.topics = ret;
							SingletonFactory.getInstance(Application).getSystemProperties().set("memcached.topics",ret);
						}});
						this.topics = curPlt.topics;
					},
					
					// From AnswerPortlet
					getAjaxTopicQuestion: function(){
						var curPlt = this;
						var curUrl = this.root + "question/get-all-un-auth-catchwords-question/qid/" + this.questionID;
						$.ajax({url:curUrl, async:false, success: function(ret){
							ret = $.parseJSON(ret);
							ret = ret.result;
							if(ret == undefined || ret == "error"){
								//console.log("Cannot get all topic")
								return;
							}
							curPlt.topicsQuestion = ret;
						}});
						this.topicsQuestion = curPlt.topicsQuestion;
					},
					
					// From AnswerPortlet
					buildQuestionTopics: function(){
						var result = $("<div><div></div></div>");
						var topicAdded = Array();
						for ( var key in this.topicsQuestion) {
							var objParam = {};
							var curObj = this.topicsQuestion[key];
							objParam.tid = generateId("tt");
							objParam.content = curObj['catchword'];
							objParam.cid = curObj['id'];
							topicAdded[this.questionID + "-" + curObj['id']] = objParam.tid;
							var newTp = tmpl("AnswerPortlet-Topic",objParam);
							result.children().append(newTp);
						}
						// fetch to cache
						var sysProp = SingletonFactory.getInstance(Application).getSystemProperties();
						sysProp.set("memcached.addedTopics",topicAdded);
						this.pendingQuestion.topics = result.children();
					},
					
					// From AnswerPortlet
					buildAllTopics: function(){
						var result = $("<div><div></div></div>");
						for ( var key in this.topics) {
							var curObj = this.topics[key];
							var newTp = $("<option value='"+curObj['id']+"'>"+curObj['catchWord']+"</option>");
							result.children().append(newTp);
						}
						this.pendingQuestion.avaiTopics = result.children();
					},
					
					// In question Pending, no other is found
					onEditPendingQuestion: function(eventData){
						this.checkUserLogin(eventData, "EditPendingQuestion");
						
					},
					
					editPendingQuestion: function(eventData){
						this.questionID = eventData.id;
						
						if(this.topics == undefined){
							this.getAjaxAllTopics();
						}
						this.getAjaxTopicQuestion();
						// dump topicsQuestions
						this.buildQuestionTopics();
						
						// dump topics
						this.buildAllTopics();
						
						// get data from cached in profilePortlet
						var pendingQuestions = SingletonFactory.getInstance(Application).getSystemProperties().get("memcached.pendingQuestions");
						var objParam = {};
						objParam.topics = this.pendingQuestion.topics || Array();
						objParam.avaiTopics = this.pendingQuestion.avaiTopics || Array();
						objParam.qcontent = pendingQuestions[this.questionID].title;
						objParam.qdetail =  pendingQuestions[this.questionID].content;
						objParam.qid =  this.questionID;
						var template = tmpl("QuestionPendingPortlet-EditQuestion", objParam);
						var tmp = $(".questionEmphasized[qid='"+this.questionID+"']").children("span");
						pendingQuestions[this.questionID]['span'] = tmp;
						SingletonFactory.getInstance(Application).getSystemProperties().set("memcached.pendingQuestions",pendingQuestions);
						$(".questionEmphasized[qid='"+this.questionID+"']").empty().append($(template));
					},
					
					//
					onSavePendingQuestions: function(eventData){
						var id = eventData.id;	
						var parent = eventData.parent;
						var title = $("#editquestion-title-" + id).val();
						var content = $("#editquestion-content-" + id).val();
						
						var curUrl = this.root + "question/update-un-auth-question";
						var sbj = SingletonFactory.getInstance(Subject);
						$
						.ajax({
							url : curUrl,
							type : "POST",
							data : {
								"content" : content,
								"title" : title,
								"qid" : id
							},
							success : function(ret) {
								var cache = SingletonFactory.getInstance(Application).getSystemProperties().get("memcached.pendingQuestions");
								var span = cache[id]['span'];
								cache[id].title = title;
								cache[id].content = content;
								SingletonFactory.getInstance(Application).getSystemProperties().set("memcached.pendingQuestions",cache);
								$(".questionEmphasized[qid='"+id+"']").empty().append("<strong>" + title + "</strong>").append(span);
								sbj.notifyEvent("NotifyGlobal",
										"Sửa thành công");
							},
							error : function(ret) {
								sbj.notifyEvent("NotifyGlobal","Sửa thất bại");
							}
						});
						
					},
					
					onCancelPendingQuestions: function(eventData){
						var id = eventData.id;	
						var cache = SingletonFactory.getInstance(Application).getSystemProperties().get("memcached.pendingQuestions");
						var span = cache[id]['span'];
						var title = cache[id].title;
						$(".questionEmphasized[qid='"+id+"']").empty().append("<strong>" + title + "</strong>").append(span);
					},

					onToggleDownEditTopic : function(eventData) {
						var id = eventData.id;
						$("#" + id).slideToggle('fast');
						$("#" + id + " #bkp-topic-search-new").val("");
						this.buildTopics(SingletonFactory.getInstance(
								Application).getSystemProperties().get(
								"memcached.topics"));
					},

					onToggleUpEditTopic : function(eventData) {
						var id = eventData.id;
						// $("#" + id).children("input[type=text]").val("");
						$("#" + id).slideToggle('fast');
					},

					// login
					onTopicAdded : function(eventData) {
						this.checkUserLogin(eventData, "TopicAdded");
					},

					topicAdded : function(eventData) {
						var id = eventData.id;
						// dang sau la pending question
						var questionID = this.questionID;
						var selected = $("#" + id + "  option:selected");
						for ( var i = 0; i < selected.length; i++) {
							var value = $(selected[i]).val();
							var text = $(selected[i]).text();

							// TODO: đưa value lên server
							// đưa value vào trong list
							// Nếu trong list có rồi thì thoi
							var topicAdded = this.app.getSystemProperties()
									.get("memcached.addedTopics");
							if (topicAdded[questionID + "-" + value] != undefined) {
								return;
							}

							var objParam = {};
							objParam.tid = generateId("tt");
							objParam.content = text;
							objParam.cid = value;
							var newTp = tmpl("AnswerPortlet-Topic", objParam);
							$("#" + id).parent().siblings(
									".bkp_question_topics").append(newTp);

							// set back to memcached
							topicAdded[questionID + "-" + value] = objParam.tid;
							var sysProp = this.app.getSystemProperties();
							sysProp.set("memcached.addedTopics", topicAdded);

							// dump to server
							var curUrl = this.root
									+ "question/add-catchword-un-auth/qid/"
									+ questionID + "/cid/" + value;
							var sbj = SingletonFactory.getInstance(Subject);
							$.ajax({
								url : curUrl,
								data : {},
								success : function(ret) {
									// console.log("Cập nhật thành công");
									sbj.notifyEvent("NotifyGlobal",
											"Thêm thành công");
								},
								error : function() {
									// console.log("Cập nhật thất bại");
									sbj.notifyEvent("NotifyGlobal",
											"Thêm thất bại");
								}
							});
						}
					},

					onTopicDeleted : function(eventData) {
						this.checkUserLogin(eventData, "TopicDeleted");
					},

					topicDeleted : function(eventData) {
						var id = eventData.id;
						var questionID = this.questionID;
						var value = $("#" + id).attr("cid")
						var text = $("#" + id + " label").text();

						var topicAdded = this.app.getSystemProperties().get(
								"memcached.addedTopics");
						topicAdded[questionID + "-" + value] = undefined;
						var sysProp = this.app.getSystemProperties();
						sysProp.set("memcached.addedTopics", topicAdded);

						$("#" + id).remove();
						// dump to server
						var curUrl = this.root
								+ "question/remove-un-auth-catchword/qid/" + questionID
								+ "/cid/" + value;
						var sbj = SingletonFactory.getInstance(Subject);
						$
								.ajax({
									url : curUrl,
									data : {},
									success : function(ret) {
										sbj.notifyEvent("NotifyGlobal",
												"Xóa thành công");
									},
									error : function() {
										sbj.notifyEvent("NotifyGlobal",
												"Xóa thất bại");
									}
								});
					},

					onTopicChanged : function(eventData) {
						var id = eventData.id;
						var pid = eventData.pid;
						var value = $("#" + id).val().trim().replace("  ", " ")
								.toLowerCase();
						var e = eventData.e;
						var topics = SingletonFactory.getInstance(Application)
								.getSystemProperties().get("memcached.topics");
						var arr = Array();
						var newTopics = null;
						var isEqual = false;
						for ( var key in topics) {
							var curObj = topics[key];
							var content = curObj['catchWord'].toLowerCase();
							var match = new RegExp(value);
							if (content == value) {
								isEqual = true;
							}
							if (match.test(content)) {
								arr.push(curObj);
							}
						}

						newTopics = this.buildTopics(arr);
						if (newTopics != null) {
							$("#" + pid).empty().append(newTopics.children());
						}
					},

					buildTopics : function(arr) {
						var result = $("<div><div></div></div>");
						for ( var key in arr) {
							var curObj = arr[key];
							var newTp = $("<option value='" + curObj['id']
									+ "'>" + curObj['catchWord'] + "</option>");
							result.children().append(newTp);
						}
						return result.children();
					},

					onCreateNewTopicContext : function(eventData) {
						this.checkUserLogin(eventData, "CreateNewContext");
					},

					checkUserLogin : function(eventData, type) {
						var evtArgs = {};
						evtArgs.type = type;
						evtArgs.evtData = eventData;
						var sbj = SingletonFactory.getInstance(Subject);
						sbj.notifyEvent("NeedLogin", evtArgs);
					},

					onRejectChanges : function(eventData) {
						var curUid = eventData.uid;
						var curAid = eventData.aid;
						$("#extension-content-plhld-" + curAid + "-" + curUid)
								.children().hide('fast');
					},

					onLoginSuccess : function(eventData) {
						var type = eventData.type;
						var evtArgs = eventData.evtData;
						if (type != undefined && evtArgs != undefined) {
							switch (type) {
							case "TopicAdded":
								this.topicAdded(evtArgs);
								break;
							case "TopicDeleted":
								this.topicDeleted(evtArgs);
								break;
							case "SubmitAnswer":
								this.submitAnswer(evtArgs);
								break;
							case "AcceptChanges":
								this.acceptChanges(evtArgs);
								break;
							case "CreateNewContext":
								this.createNewContextSuccess(evtArgs);
								break;
							case "EditPendingQuestion":
								this.editPendingQuestion(evtArgs);
								break;
							default:
								break;
							}
						}
					},

					createNewContextSuccess : function() {
						var subject = SingletonFactory.getInstance(Subject);
						var rq = SingletonFactory.getInstance(Page)
								.getRequest();
						var params = rq.getParams();
						var request = new Request("TopicCreatePage", "", {
							"pageCallBack" : params["page"],
							"needParam" : true
						});
						subject.notifyEvent('RequestRoute', request);
					},

					onHtmlUpdated : function() {
						var id = SingletonFactory.getInstance(Application)
								.getSystemProperties().get("user.id");
						$(
								".extension-point[extensionName='ProfileImageCheck'][uid='"
										+ id + "']").css("background-color",
								"#FAFAFA");
					}

				}).implement(PluginInterface);

/**
 * 
 */

MoreContentPlugin = Class.extend(
		{
			init : function() {
				this.name = "MoreContentPlugin";
			},

			onHtmlRendered : function(eventData) {
				//this.render(eventData);
			},
			
			onCheckMoreLessContent: function(eventData){
				this.render(eventData);
			},
			
			render : function(eventData) {
// $('.extension-point[extensionName="MoreContent"]').each(function(){
				var showChar = 120;
				var ellipsestext = "...";
				var moretext = "(more)";
				var lesstext = "(less)";
				var index = 0;
				$('.show_more_content').each(function() {
					index++;
				    var content = $(this).html();
				    var curChildren = $(this).children();
				    var lengthChildren = curChildren.length;
				    if(lengthChildren == 0){
				  	   if(content.length > showChar) {
				           var c = content.substr(0, showChar);
				           var h = content.substr(showChar-1, content.length - showChar);
				           var html = c + '<span class="moreellipses">' + ellipsestext+ '&nbsp;</span><span class="morecontent"><span>' + h + '</span>&nbsp;&nbsp;<a href="" class="morelink">' + moretext + '</a></span>';
				           $(this).html(html);
				       }
				    } 
				    else {
						for(var i=0; i< lengthChildren; i++){
							var curContent = $(curChildren[i]).html().trim();
							if(curContent == ""){
								continue;
							}
							
							var tmp = $("<div></div>").append(curContent.substring(0,showChar)); 
				    		var other = $("<div></div>").append(curChildren);
				    		if(content.length > showChar) {
				    			var html = '<span class="showmorecontent">' + tmp.html() + '</span><span class="moreellipses">' + ellipsestext+ '&nbsp;</span><span class="hiddencontentwithtags" style="display:none">' + other.html() + '</span><span class="morecontentwithtags"><a class="morelinkwithtags">' + moretext + '</a></span>';
				    			$(this).html(html);
					    	}
							break;
						}
				    }
				       
				   });
				
				   $(".morelink").click(function(){
				       if($(this).hasClass("less")) {
				           $(this).removeClass("less");
				           $(this).html(moretext);
				       } else {
				           $(this).addClass("less");
				           $(this).html(lesstext);
				       }
				       $(this).parent().prev().toggle();
				       $(this).prev().toggle();
				       return false;
				   });
				   
				   $(".morelinkwithtags").click(function(){
				       var hiddenItem = $(this).parent().siblings(".hiddencontentwithtags");
				       var hiddenItemContent = hiddenItem.html();
				       var showItem = $(this).parent().siblings(".showmorecontent");
				       var shownItemContent = showItem.html();
				       hiddenItem.empty().append(shownItemContent);
				       showItem.empty().append(hiddenItemContent);

				       if($(this).hasClass("lessContent")) {
				           $(this).removeClass("lessContent");
				           $(this).parent().siblings(".moreellipses").html(ellipsestext+"&nbsp;");
				           $(this).html(moretext);
				       } else {
				           $(this).addClass("lessContent");
				           $(this).parent().siblings(".moreellipses").html("");
				           $(this).html(lesstext);
				       }
				       return false;
				   });
			}
			
//			onCheckMoreLessContent: function(eventData){
//				var showChar = 120;
//				var ellipsestext = "...";
//				var moretext = "(more)";
//				var lesstext = "(less)";
//				var index = 0;
//				
//				$(eventData).find('.show_more_content').each(function(index,value) {
//					value = $(value);
//					index++;
//				    var content = $(value).html();
//				    var curChildren = $(value).children();
//				    var lengthChildren = curChildren.length;
//				    if(lengthChildren == 0){
//				  	   if(content.length > showChar) {
//				           var c = content.substr(0, showChar);
//				           var h = content.substr(showChar-1, content.length - showChar);
//				           var div = $("<div></div>");
//				           var a1 = $(c + '<span class="moreellipses">' + ellipsestext+ '&nbsp;</span>');
//				           var a2 = $('<span class="morecontent"><span>' + h + '</span>&nbsp;&nbsp;</span>');
//				           var a3 = $('<a href="" class="morelink">' + moretext + '</a>');
//				           a3.click(function(){
//				        	   if($(this).hasClass("less")) {
//						           $(this).removeClass("less");
//						           $(this).html(moretext);
//						       } else {
//						           $(this).addClass("less");
//						           $(this).html(lesstext);
//						       }
//						       $(this).parent().prev().toggle();
//						       $(this).prev().toggle();
//						       return false;
//				           });
//				           $(a2).append(a3);
//				           div.append(a1).append(a2);
//				           $(value).empty.append(div.children());
//				       }
//				    } 
//				    else {
//				    	var tmp = $("<div></div>").append($(curChildren[0]).html().substring(0,showChar)); 
//				    	var other = $("<div></div>").append(curChildren);
//				    	if(content.length > showChar) {
//				    		var a1 = $('<span class="showmorecontent">' + tmp.html() + '</span><span class="moreellipses">' + ellipsestext+ '&nbsp;</span><span class="hiddencontentwithtags" style="display:none">' + other.html() + '</span>');
//				    		var a2 = $('<span class="morecontentwithtags"></span>');
//				    		var a3 = $('<a class="morelinkwithtags">' + moretext + '</a>');
//				    		a3 = $(a3).click(function(){console.log("adsf");
//				    			var hiddenItem = $(this).parent().siblings(".hiddencontentwithtags");
//							       var hiddenItemContent = hiddenItem.html();
//							       var showItem = $(this).parent().siblings(".showmorecontent");
//							       var shownItemContent = showItem.html();
//							       hiddenItem.empty().append(shownItemContent);
//							       showItem.empty().append(hiddenItemContent);
//
//							       if($(this).hasClass("lessContent")) {
//							           $(this).removeClass("lessContent");
//							           $(this).parent().siblings(".moreellipses").html(ellipsestext+"&nbsp;");
//							           $(this).html(moretext);
//							       } else {
//							           $(this).addClass("lessContent");
//							           $(this).parent().siblings(".moreellipses").html("");
//							           $(this).html(lesstext);
//							       }
//							       return false;
//				    		});
//				    		a2 = $(a2).append(a3);
//				    		$(value).empty().append($(a1)).append($(a2));
//					    } 
//				    }
//				   });
//			}
		}).implement(PluginInterface);
/**
 * 
 */

SearchResHelperPlugin = Class.extend({
	init : function() {
		this.name = "SearchResHelperPlugin";
	},
	
	checkTopics: function(eventData){
		$('.extension-point[extensionName="CheckTopicsAvai"]').each(function(){
			var children = $(this).children("a"); 
			var length = children.length;
			var shown = 4;
			children.slice(shown,length).remove();
			if(length > shown){
				$(this).append("<label style='color:#666666'>...</label>");
			}
		});
	},

	checkContentAvai: function(eventData){
		$('.extension-point[extensionName="CheckContentAvai"]').each(function(){
			var html = $(this).find(".show_more_content").html().trim();
			if(html != ""){
				$(this).css("display","inline-block");
			}
		});
	},
	
	localCheckTopic: function(eventData){
		$(eventData).find('.extension-point[extensionName="CheckTopicsAvai"]').each(function(index,value){
			var children = $(value).children("a"); 
			var length = children.length;
			var shown = 4;
			children.slice(shown,length).remove();
			if(length > shown){
				$(value).append("<label style='color:#666666'>...</label>");
			}
		});
	},
	
	localCheckContentAvai: function(eventData){
		$(eventData).find('.extension-point[extensionName="CheckContentAvai"]').each(function(index,value){
			var html = $(value).find(".show_more_content").html().trim();
			if(html != ""){
				$(value).css("display","inline-block");
			}
		});
	},
	
	onHtmlRendered : function(eventData) {
		this.checkContentAvai(eventData);
		this.checkTopics(eventData);
	},
	
	onRequestCheckAnswerContent: function(eventData){
		this.localCheckContentAvai(eventData);
		this.localCheckTopic(eventData);
	}
}).implement(PluginInterface);
QuestionFollowPortlet = Class.extend({
	init: function()	{
		this.name = "QuestionFollowPortlet";
	},
	
	onReloadPage: function()	{
		this.run();
	},
	
	onBegin: function()	{
		this.registerObserver();
	},
	
	onUnfollowQuestion: function(eventData)	{
		var qid = eventData.qid;
		var obj = this;
		this.onAjax('question', 'unfollow-question', {'id': qid}, 'POST', {
			'onSuccess': function(ret)	{
				obj.onReloadPage();
			}
		});
	},
	
	onFollowQuestion: function(eventData)	{
		var qid = eventData.qid;
		var obj = this;
		this.onAjax('question', 'follow-question', {'id': qid}, 'POST', {
			'onSuccess': function(ret)	{
				obj.onReloadPage();
			}
		});
	},
	
	run: function()	{
		var obj = this;
		var qid = this.getRequest().getParam('qid');
		this.onAjax('question', 'is-user-following', {'id': qid}, 'GET', {
			'onSuccess': function(ret)	{
				obj.model = {};
				obj.model.qid = qid;
				if (ret == true)	{
					obj.model.text = "Ngừng theo dõi câu hỏi";
					obj.model.event = "UnfollowQuestion";
				} else {
					obj.model.text = "Theo dõi câu hỏi";
					obj.model.event = "FollowQuestion";
				}
				obj.getPortletPlaceholder().paintCanvas(obj.render());
			}
		});
	},
	
	onEnd: function()	{
		this.unregisterObserver();
	}
}).implement(PortletInterface).implement(AjaxInterface).implement(RenderInterface).implement(ObserverInterface);
StatsPortlet = Class.extend({
	init: function()	{
		this.name = "StatsPortlet";
		this.interval = 300000;
	},
	
	onBegin: function()	{
		this.model = {};
	},
	
	run: function()	{
		this.getPortletPlaceholder().drawToCanvas(this.render());
		this.fetch();
		this.startInterval(this.interval, this.fetch);
	},
	
	fetch: function()	{
		var obj = this;
		this.onAjax('ajax', 'count-users', {}, 'GET', {
			'onSuccess': function(ret)	{
				obj.requestForEffectiveResource('UserTotal').html(ret);
			}
		});
		this.onAjax('ajax', 'count-questions', {}, 'GET', {
			'onSuccess': function(ret)	{
				obj.requestForEffectiveResource('QuestionTotal').html(ret);
			}
		});
		this.onAjax('ajax', 'count-answers', {}, 'GET', {
			'onSuccess': function(ret)	{
				obj.requestForEffectiveResource('AnswerTotal').html(ret);
			}
		});
	},
	
	onEnd: function()	{
		this.stopInterval();
	}
}).implement(PortletInterface).implement(AjaxInterface).implement(RenderInterface).implement(IntervalTimerInterface);

HallOfFamePortlet = StatsPortlet.extend({
	init: function()	{
		this._super();
		this.name = "HallOfFamePortlet";
	},
	
	fetch: function()	{
		var obj = this;
		this.onAjax('ajax', 'get-most-voted-user', {}, 'GET', {
			'onSuccess': function(ret)	{
				obj.requestForEffectiveResource('MostVoted').html(ret.name);
				obj.requestForEffectiveResource('MostVoted').attr('href', "#page/Profile/id/"+ret.id);
				obj.requestForEffectiveResource('MostVotedAvatar').attr('src', 'avatar/'+ret.avatar);
				obj.requestForEffectiveResource('MostVotedCount').html(ret.total);
			}
		});
		this.onAjax('ajax', 'get-most-answer-user', {}, 'GET', {
			'onSuccess': function(ret)	{
				obj.requestForEffectiveResource('MostAnswer').html(ret.name);
				obj.requestForEffectiveResource('MostAnswer').attr('href', "#page/Profile/id/"+ret.id);
				obj.requestForEffectiveResource('MostAnswerAvatar').attr('src', 'avatar/'+ret.avatar);
				obj.requestForEffectiveResource('MostAnswerCount').html(ret.total);
			}
		});
	}
}).implement(PortletInterface).implement(AjaxInterface).implement(RenderInterface).implement(IntervalTimerInterface);

FeedbackListPortlet = StatsPortlet.extend({
	init: function()	{
		this.name = "FeedbackListPortlet";
		this.interval = 600000;
	},
	
	run: function()	{
		this.fetch();
		this.startInterval(this.interval, this.fetch);
	},
	
	fetch: function()	{
		var obj = this;
		this.onAjax('ajax', 'get-feedback-list', {}, 'GET', {
			'onSuccess': function(ret)	{
				obj.model = {};
				//console.log(ret);
				obj.model.feedbacks = ret;
				obj.getPortletPlaceholder().paintCanvas(obj.render());
			}
		});
	}
}).implement(PortletInterface).implement(AjaxInterface).implement(RenderInterface).implement(IntervalTimerInterface);;
TopicPageMainPortlet = Class.extend({
	init: function()	{
		this.name = "TopicPageMainPortlet";
	},
	
	onReloadPage: function()	{
		this.run();
	},
	
	run: function()	{
		var subject = SingletonFactory.getInstance(Subject);
		var id = this.getRequest().getParam('id');
		if (id == undefined || isNaN(id))	{
			subject.notifyEvent('RequestRoute', new Request('ErrorPage', undefined, {'code':404}));
			return;
		}
		var obj = this;
		obj.model = {};
		obj.getPortletPlaceholder().paintCanvas(obj.render());
		this.onAjax('catchword', 'get-topic-details', {'id':id}, 'GET', {
			'onSuccess': function(ret)	{
				obj.requestForEffectiveResource('Header').html(ret.catchWord);
				obj.requestForEffectiveResource('Detail').html(ret.detail);
			},
			
			'onFailure': function(message)	{
				subject.notifyEvent('RequestRoute', new Request('ErrorPage', undefined, {'code':404}));
			}
		});
		
		this.onAjax('catchword', 'count-topic-experts', {'id':id}, 'GET', {
			'onSuccess': function(ret)	{
				obj.requestForEffectiveResource('Footer').prepend(obj.renderView('ExpertsCount', {'count': ret}));
			}
		});
		
		this.onAjax('catchword', 'get-most-voted-topic-expert', {'id':id}, 'GET', {
			'onSuccess': function(ret)	{
				obj.requestForEffectiveResource('Footer').append(obj.renderView('MostVotedExperts', ret));
			}
		});
	}
}).implement(PortletInterface).implement(RenderInterface).implement(AjaxInterface);
/**
 * 
 */

LoginPortlet = Class.extend({
	
	init: function()	{
		this.name = "LoginPortlet";
		this.model = {};
	},
	
	onBegin: function()	{
		this.registerObserver();
	},
	
	onNeedLogin: function(eventData)	{
		this.currentEventData = eventData;
		//console.log("Need Login");
		//check login?
		var properties = SingletonFactory.getInstance(Application).getSystemProperties();
		var root = properties.get('host.root');
		var loggedIn = properties.get('user.login', undefined);
		var obj = this;
		//no evidence found
		if (loggedIn == undefined)	{
			//query to server
			this.onAjax('ajax', 'check-user-status', {}, 'GET', 
					{'onSuccess': function(ret)	{
						if (ret == 0)	{
							properties.set('user.login', 0, true);
						} else {
							properties.set('user.login', 1, true);
							properties.set('user.id', ret.userid, true);
							properties.set('user.name', ret.name, true);
						}
						obj.recheckLogin(eventData);
					}});
		} else {
			this.recheckLogin(eventData);
		}
	},
	
	recheckLogin: function(eventData)	{
		var subject = SingletonFactory.getInstance(Subject);
		var properties = SingletonFactory.getInstance(Application).getSystemProperties();
		var loggedIn = properties.get('user.login', undefined);
		if (loggedIn == 0)	{
			this.model.loginError = this.getLocalizedText('NeedLogin');
			$.facebox(this.render());
		} else {
			subject.notifyEvent('LoginSuccess', eventData);
		}
	},
	
	onPasswordTextBoxKeyUp: function(event)	{
		var keycode = event.keyCode;
		if (keycode == 13)	{
			this.onLoginButtonClick(event);
		}
	},
	
	onLoginButtonClick: function(eventData)	{
		var target = eventData.target;
		var form = $(target).parents('.login:first');
		//ajax request
		var username = $(form).find('#LoginPortlet-Username').val();
		var password = $(form).find('#LoginPortlet-Password').val();
		var remember = $(form).find('#LoginPortlet-Persistent:checked').length;
		var loginError = $(target).parents('.loginInnerForm:first').find('#LoginPortlet-LoginError');
		if (username == '' || password == '')	{
			$(loginError).html(this.getLocalizedText('LoginInsufficientInput'));
		}
		var obj = this;
		this.onAjax('ajax', 'login', {'username':username, 'password':password, 'persistent': remember}, 'POST', 
				{'onSuccess': function(ret)	{
					var properties = SingletonFactory.getInstance(Application).getSystemProperties();
					properties.set('user.login', 1, true);
					properties.set('user.id', ret.userid, true);
					properties.set('user.name', ret.name, true);
					//FIXME: Close facebox
					var facebox = $(target).parents('#facebox');
					if (facebox != undefined)	{
						$.facebox.close();
					}
					var subject = SingletonFactory.getInstance(Subject);
					subject.notifyEvent('LoginSuccess', obj.currentEventData);
				},
				'onFailure': function(message)	{
					$(loginError).html(message);
				}});
	},
	
	run: function()	{
		this.model.loginError = '';
		this.getPortletPlaceholder().drawToCanvas(this.render());
	}
}).implement(RenderInterface).implement(PortletInterface).implement(ObserverInterface).implement(AjaxInterface);

RegisterPortlet = Class.extend({
	init: function()	{
		this.name = "RegisterPortlet";
		this.step = 1;
		this.subject = SingletonFactory.getInstance(Subject);
	},
	
	onBegin: function()	{
		this.model = {};
		this.model.welcomeMsg = this.getLocalizedText('Welcome');
		this.model.nameMsg = this.getLocalizedText('Name');
		this.model.usernameMsg = this.getLocalizedText('Username');
		this.model.passwordMsg = this.getLocalizedText('Password');
		this.model.repasswordMsg = this.getLocalizedText('Repassword');
		this.model.emailMsg = this.getLocalizedText('Email');
		this.model.submitMsg = this.getLocalizedText('Submit');
		this.model.skipMsg = this.getLocalizedText('Skip');
		this.model.registerMsg = this.getLocalizedText('Register');
		this.model.additionInfoMsg = this.getLocalizedText('AdditionInfo');
		this.model.expertiseMsg = this.getLocalizedText('Expertise');
		this.model.tokenMsg = this.getLocalizedText('Token');
		
		this.model.usernameTitle = this.getLocalizedText('UsernameTitle');
		this.model.passwordTitle = this.getLocalizedText('PasswordTitle');
		this.model.repasswordTitle = this.getLocalizedText('RepasswordTitle');
		this.model.emailTitle = this.getLocalizedText('EmailTitle');
		this.registerObserver();
		this.buildTemplate();
	},
	
	buildTemplate: function()	{
		var rootNode = this.requestForResource('ProfileStructure');
		var placeholder = this.requestForResource('ProfileMainContent');
		this.subject.notifyEvent('BuildProfileTemplate', {'id': this.name, 'root':rootNode, 'placeholder': placeholder});
	},
	
	run: function()	{
		this.model.existUsername = "";
		this.model.existEmail = "";
		this.step1();
	},
	
	step1: function()	{
		this.getPortletPlaceholder().drawToCanvas(this.renderView('ViewStep1', this.model));
	},
	
	onRegisterButtonClick: function(eventData)	{
		var fullname = this.requestForEffectiveResource('Name').val();
		var username = this.requestForEffectiveResource('Username').val();
		var password = this.requestForEffectiveResource('Password').val();
		var repassword = this.requestForEffectiveResource('Repassword').val();
		var email = this.requestForEffectiveResource('Email').val();
		var token = this.requestForEffectiveResource('Token').val();
		
		var obj = this;
		obj.requestForEffectiveResource('RegisterError').html('');
		//console.log('register button click');
		this.onAjax('ajax', 'register', {'username':username, 'password':password, 'repassword':repassword, 'email':email, 'fullname':fullname, 'token': token}, 'POST', 
				{onSuccess: function(ret)	{
					obj.profile_id = ret.profile_id;
					obj.step2();
					},
				onFailure: function(message)	{
					//console.log('fail!');
					var err = {};
					err.errors = message;
					var errMsg = obj.getLocalizedText('RegisterError');
					obj.requestForEffectiveResource('RegisterError').html(errMsg+obj.renderView('Errors', err));
				}});
	},
	
	step3: function()	{
		this.getPortletPlaceholder().paintCanvas(this.renderView('ViewStep3', this.model));
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent('RenderExpertiseEditor', {placeholder:this.requestForEffectiveResource('ExpertisePlaceholder'), namespace:'RegisterPortlet'});
	},
	
	step2: function()	{
		this.getPortletPlaceholder().paintCanvas(this.renderView('ViewStep2', this.model));
		this.requestForEffectiveResource('ProfileEdit').html(this.requestForResource('ViewData').html());
		this.subject.notifyEvent('DisplayRemainingNodes', {'id': this.name});
		this.subject.notifyEvent('NeedFormatting');
		this.subject.notifyEvent("ProfileInputBindEvent");
	},
	
	onSkipExpertiseRegisterButtonClick: function(eventData)	{
		this.end();
	},
	
	onSubmitExpertiseRegisterButtonClick: function(eventData)	{
		var expToSent = Array();
		var container = this.requestForMatchingEffectiveResource('ListExpertise', '.tokenContainer');
		$(container).find('label.lblToken').each(function(index, value)	{
			var id = $(value).attr('eid');
			expToSent.push(id);
		});
		
		var intToSent = Array();
		var container = this.requestForMatchingEffectiveResource('ListInterestedArea', '.tokenContainer');
		$(container).find('label.lblToken').each(function(index, value)	{
			var id = $(value).attr('eid');
			intToSent.push(id);
		});
		intToSent = $.toJSON(intToSent);
		expToSent = $.toJSON(expToSent);
		var obj = this;
		this.onAjax('ajax', 'add-expertise', {'experts': expToSent, 'interests': intToSent}, 'POST', 
				{'onSuccess': function(ret)	{
					obj.end();
				}});
	},
	
	onEnd: function()	{
		this.unregisterObserver();
	},
	
	end: function()	{
		var request = new Request("Home");
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent('RequestRoute', request);
	},
	
	onSkipEditRegisterButtonClick: function(eventData)	{
		this.step3();
	},
	
	onSubmitEditRegisterButtonClick: function(eventData)	{
		var root = this.requestForEffectiveResource('ProfileEdit');
		var dataToSent = {};
		dataToSent.profile_id = this.profile_id;
		dataToSent.data = Array();
		var obj = this;
		$(root).find('.profileData').each(function(index, value)	{
			var ancestor = $(value).parents('[rootname]:first');
			var prop_key = $(ancestor).attr('oid');
			if (prop_key == undefined || prop_key == '' || isNaN(prop_key))
				prop_key = $(ancestor).attr('rootname');
			var ancestorParent = $(ancestor).parents('[rootname]:first');
			var parent_key = $(ancestorParent).attr('oid');
			if (parent_key == undefined || parent_key == '' || isNaN(parent_key))
				parent_key = $(ancestorParent).attr('rootname');
			
			var formatter = $(value).attr('formatter');
			var prop_val = "";
			if (formatter == 'Normal' || formatter == 'NormalLarge')	{
				if ($(value).attr('modified') == 'true')	{
					prop_val = $(value).val();
					var partial = obj.buildSavingData(prop_key, prop_val, parent_key);
					dataToSent.data.push(partial);
				}
				return;
			} else if (formatter == 'Date')	{
				prop_val = $(value).val();
			} else if (formatter == 'Enum')	{
				prop_val = $(value).find('input:checked').attr('value');
				if (prop_val == undefined)	{
					prop_val = '';
				}
			} else if (formatter == 'List' || formatter == 'Email' )	{
				var listData = Array();
				$(value).find('label.lblToken').each(function(i, v)	{
					var val = $(v).html();
					var partial = obj.buildSavingData(prop_key, val, parent_key);
					dataToSent.data.push(partial);
				});
				return;
			}
			var partial = obj.buildSavingData(prop_key, prop_val, parent_key);
			dataToSent.data.push(partial);
		});
		obj.requestForEffectiveResource('RegisterEditSuccess').html('');
		obj.requestForEffectiveResource('RegisterEditError').html('');
		dataToSent = $.toJSON(dataToSent);
		//console.log(dataToSent);
		this.onAjax('ajax', 'commit-profile', {'data': dataToSent}, 'POST', 
				{'onSuccess': function(ret)	{
					var successMsg = obj.getLocalizedText('RegisterEditSuccess');
					obj.requestForEffectiveResource('RegisterEditSuccess').html(successMsg);
					obj.step3();
					},
				'onFailure': function(message)	{
//						var errorMsg = obj.getLocalizedMessage('RegisterEditError', message);
//						obj.requestForEffectiveResource('RegisterEditError').html(errorMsg);
						obj.step3();
					}});
	},
	
	buildSavingData: function(prop_key, prop_val, parent_key)	{
		var partial = {};
		partial.prop_key = prop_key;
		partial.prop_val = prop_val;
		partial.parent_key = parent_key;
		return partial;
	}
}).implement(PortletInterface).implement(RenderInterface).implement(ObserverInterface).implement(AjaxInterface);
LinksPortlet = Class.extend({
	init: function()	{
		this.name = "LinksPortlet";
	},
	
	onBegin: function()	{
		this.model = {};
	},

	run: function()	{
		this.getPortletPlaceholder().drawToCanvas(this.render());
	}
}).implement(PortletInterface).implement(RenderInterface);

InviteLinkPortlet = Class.extend({
	init: function()	{
		this.name = "InviteLinkPortlet";
	},
	
	onBegin: function()	{
		this.model = {};
	},

	run: function()	{
		this.getPortletPlaceholder().drawToCanvas(this.render());
	}
}).implement(PortletInterface).implement(RenderInterface);
TwitterFollowPortlet = Class.extend({
	init: function()	{
		this.name = "TwitterFollowPortlet";
	},
	
	onBegin: function()	{
		this.model = {};
	},

	run: function()	{
		this.getPortletPlaceholder().drawToCanvas(this.render());
	}
}).implement(PortletInterface).implement(RenderInterface);

ContactPortlet = Class.extend({
	init: function()	{
		this.name = "ContactPortlet";
	},
	
	onBegin: function()	{
		this.model = {};
	},

	run: function()	{
		this.getPortletPlaceholder().drawToCanvas(this.render());
	}
}).implement(PortletInterface).implement(RenderInterface);

CatchWordBrowserPortlet = Class.extend({
	init: function()	{
		this.name = "CatchWordBrowserPortlet";
	},
	
	run: function()	{
		var obj = this;
		this.onAjax('catchword', 'browse-catch-word', {}, 'GET', {
			'onSuccess': function(ret)	{
				obj.model = {};
				obj.model.catchwords = Array();
				for(var i in ret)	{
					var row = ret[i];
					var contextID = row.contextID;
					if (typeof obj.model.catchwords[contextID] == 'undefined')	{
						obj.model.catchwords[contextID] = {};
						obj.model.catchwords[contextID].context = row.context;
						obj.model.catchwords[contextID].catches = Array();
					}
					obj.model.catchwords[contextID].catches.push(row);
				}
				obj.getPortletPlaceholder().drawToCanvas(obj.render());
			}
		});
	}
}).implement(PortletInterface).implement(RenderInterface).implement(AjaxInterface);

TwitterUpdatePortlet = Class.extend({
	init: function()	{
		this.name = "TwitterUpdatePortlet";
	},
	
	run: function()	{
//		var template = $('<script></script>').append($(this.requestForResource('TwitterRender')).html());
//		this.getPortletPlaceholder().drawToCanvas(template);
	}
}).implement(PortletInterface).implement(RenderInterface);

BrowserTogglePlugin = Class.extend({
	init: function()	{
		this.name = "BrowserTogglePlugin";
	},
	
	onToggleBrowserContext: function(event)	{
		var target = event.target;
		$(target).parent().parent().find('.catchwords-placeholder').toggle();
	},
	
	onHtmlUpdated: function()	{
		$('.extension-point[extensionName="ContextBrowser"]').each(function(index, value) {
			if ($(value).find('div[flag="ContextBrowserToggle"]').length > 0)	{
				return;
			}
			$(value).append(tmpl('ContextBrowserToggle', {}));
			$(value).parent().find('.catchwords-placeholder').toggle();
		});
	}
}).implement(PluginInterface);
ProfileFinishPortlet = Class.extend({
	init: function()	{
		this.name = "ProfileFinishPortlet";
	},
	
	run: function()	{
		var obj = this;
		this.onAjax('user-ajax', 'check-finish-profile', {}, 'GET', {
			'onSuccess': function(ret)	{
				obj.model = {};
				obj.model.finish = 25;
				obj.model.msgs = '';
				if(ret.avatar != false) obj.model.finish += 25;
				else obj.model.msgs += 'Bạn chưa cập nhật hình đại diện?<br />';
				if(ret.catches != false) obj.model.finish += 25;
				else obj.model.msgs += 'Bạn chưa cập nhật kinh nghiệm?<br />';
				if(ret.interest != false) obj.model.finish += 25;
				else obj.model.msgs += 'Bạn chưa cập nhật lĩnh vực quan tâm?<br />';
				if(ret.question != false);// obj.model.finish += 20;
				else obj.model.msgs += '<span onclick=\'generateEvent("MakeNewQuestion", {})\' class="link">Bạn chưa  đặt câu hỏi nào?<span><br />';
				if(obj.model.finish<100)
					obj.model.msgs += '';
				obj.getPortletPlaceholder().drawToCanvas(obj.render());
			}
		});
	}
}).implement(PortletInterface).implement(RenderInterface).implement(AjaxInterface);
/**
 * Trunghieu 
 */

DemoPortlet = Class.extend({
	init : function(){
		this.name = "DemoPortlet";
	},
	
	onReloadPage: function()	{
		this.run();
	},
	
	run: function(){
		this.getPortletPlaceholder().paintCanvas('');
		var loggedin = SingletonFactory.getInstance(Application).getSystemProperties().get('user.login');
		if (loggedin == 1)	{
			return;
		}
		this.getPortletPlaceholder().drawToCanvas(this.render());
		//console.log("slide");
		$(this.requestForEffectiveResource('Slide')).anythingSlider({
		 	width: 960,
		 	hashTags: false,
		 	navigationFormatter : function(index, panel){ // Format navigation labels with text
				return ['Đăng ký', 'Tìm kiếm', 'Đặt câu hỏi', 'Trả lời câu hỏi'][index - 1];
			}
		 }); // add any non-default options here
//		this.getPortletPlaceholder().getCanvas().access().css("margin-left","-18px"); 
//		$('#bkp_middle_main').css('width','100%');
	}
}).implement(RenderInterface).implement(PortletInterface); 
FeedbackPortlet = Class.extend({
	init: function()	{
		this.name = "FeedbackPortlet";
	},
	
	onBegin: function()	{
		this.model = {};
		this.registerObserver();
	},
	
	run: function()	{
		this.getPortletPlaceholder().drawToCanvas(this.render());
	},
	
	onFeedbackSubmit: function()	{
		var feedback = this.requestForEffectiveResource('TextInput').val().trim();
		var location = window.location.href;
		if (feedback == "")	{
			var obj = this.requestForEffectiveResource('Error');
			$(obj).val(this.getLocalizedText('FeedbackError'));
			return;
		}
		var email = this.requestForEffectiveResource('Email').val().trim();
		var obj = this;
		this.onAjax('ajax', 'simple-feedback', {'content': feedback, 'location': location, 'email': email}, 'POST', {
			'onSuccess': function(ret)	{
				var subject = SingletonFactory.getInstance(Subject);
				subject.notifyEvent('NotifyGlobal', 'Cảm ơn bạn đã đóng góp cho hệ thống! Chúng tôi sẽ nghiên cứu phản hồi của bạn và cải thiện hệ thống cho phù hợp');
				var request = new Request('Home');
				subject.notifyEvent('RequestRoute', request);
			},
			'onFailure': function(message)	{
				var error = obj.requestForEffectiveResource('Error');
				$(error).html(obj.getLocalizedText('FeedbackSubmitError'));
			}
		});
	},
	
	onEnd: function()	{
		this.unregisterObserver();
	}
}).implement(PortletInterface).implement(RenderInterface).implement(ObserverInterface).implement(AjaxInterface);
/**
 * @author: TrungHieu
 */

StaticContentPortlet = Class.extend({
	init:function() {
		this.name = "StaticContentPortlet";
		this.ids = new Array("AboutUs","Tutorial","Faq","Tou","Piracy","Architecture");
		this.request = {};
	},
	
	displayContent: function(){
		var page = SingletonFactory.getInstance(Page);
		var request = page.getRequest();
		var container = SingletonFactory.getInstance(PortletContainer);
		var footer = container.getPortletMetaByName("FooterPortlet").portlet;
		if(request.getParam("page") == "Documentation"){
			id = request.getParam("id");
			if(this.requestForEffectiveResource(id) == undefined){
				//console.log(id);
			}
			for( var i=0; i<this.ids.length; i++ ){
				if(!this.requestForEffectiveResource(this.ids[i]).hasClass("doNotDisplay")){
					this.requestForEffectiveResource(this.ids[i]).addClass("doNotDisplay");
				}
			}
			this.requestForEffectiveResource(id).removeClass("doNotDisplay");
			footer.setActive(id);
		}
	},
	
	onReloadPage: function(){
		this.displayContent();
	},
	
	run: function() {
		this.getPortletPlaceholder().drawToCanvas(this.render());
		this.displayContent();
	}
}).implement(RenderInterface).implement(PortletInterface);
EmailPasswdEditPortlet = Class.extend({
	init: function()	{
		this.name = "EmailPasswdEditPortlet";
	},
	
	onBegin: function()	{
		this.registerObserver();
	},
	
	onUserCPButtonClick: function()	{
		var curPass = this.requestForEffectiveResource('CurrentPasswd').val().trim();
		var pass = this.requestForEffectiveResource('Passwd').val().trim();
		var confirmPass = this.requestForEffectiveResource('ConfirmPasswd').val().trim();
		var email = this.requestForEffectiveResource('Email').val().trim();
		
		this.requestForEffectiveResource('Error').html('');
		var obj = this;
		this.onAjax('user-ajax', 'edit-email-password', {'currentPasswd': curPass, 'passwd': pass, 'confirmPassword': confirmPass, 'email':email}, 'POST', {
			'onSuccess': function(ret)	{
				var subject = SingletonFactory.getInstance(Subject);
				subject.notifyEvent('NotifyGlobal', 'Bạn đã thay đổi thông tin cá nhân thành công!');
				subject.notifyEvent('RequestRoute', new Request('User'));
			},
			'onFailure': function(message)	{
				var err = {};
				err.errors = message;
				obj.requestForEffectiveResource('Error').html(obj.renderView('ErrorView', err));
			}
		});
	},
	
	run: function()	{
		var obj = this;
		this.onAjax('user-ajax', 'get-user-email', {}, 'GET', {
			'onSuccess': function(ret)	{
				obj.model = {};
				obj.model.email = ret;
				obj.getPortletPlaceholder().paintCanvas(obj.render());
			}
		});
	},
	
	onEnd: function()	{
		this.unregisterObserver();
	}
}).implement(PortletInterface).implement(RenderInterface).implement(AjaxInterface).implement(ObserverInterface);

EmailRecoverPortlet = Class.extend({
	init: function()	{
		this.name = "EmailRecoverPortlet";
	},
	
	onBegin: function()	{
		this.registerObserver();
	},
	
	onRecoverButtonClick: function()	{
		var obj = this;
		var captchaResponse = $('input#recaptcha_response_field').val();
		var captchaChallenge = $('input#recaptcha_challenge_field').val();
		var email = this.requestForEffectiveResource('Email').val();
		this.requestForEffectiveResource('Email').attr('disabled', 'true');
		this.requestForEffectiveResource('Error').html('<img src="static/images/ajax-loader-1.gif">');
		
		this.onAjax('user-ajax', 'request-new-password', 
				{'recaptcha_challenge_field': captchaChallenge, 'recaptcha_response_field': captchaResponse,
					'email': email}, 'POST', {
						'onSuccess': function()	{
							var subject = SingletonFactory.getInstance(Subject);
							subject.notifyEvent('NotifyGlobal', 'Chúng tôi đã gửi hướng dẫn phục hồi mật khẩu đến email của bạn! Hướng dẫn có giá trị trong vòng 24h');
							subject.notifyEvent('RequestRoute', new Request('Home'));
						},
						
						'onFailure': function(message)	{
							obj.requestForEffectiveResource('Email').removeAttr('disabled');
							obj.requestForEffectiveResource('Error').html(message);
						}
					});
	},
		
	run: function()	{
		this.getPortletPlaceholder().paintCanvas(this.requestForResource('View').html());
		Recaptcha.create("6LeF-MISAAAAAKXfmjbbhb-EO5wSfJK3qkRBfGD_",
			    this.name+"-Recaptcha",
			    {
			      theme: "red",
			      callback: Recaptcha.focus_response_field
			    }
			  );
	},
	
	onEnd: function()	{
		this.unregisterObserver();
	}
}).implement(PortletInterface).implement(RenderInterface).implement(AjaxInterface).implement(ObserverInterface);

PasswordResetPortlet = Class.extend({
	init: function()	{
		this.name = "PasswordResetPortlet";
	},
	
	onBegin: function()	{
		this.registerObserver();
	},
	
	onReloadPage: function()	{
		this.run();
	},
	
	onResetButtonClick: function()	{
		var obj = this;
		var pw = this.requestForEffectiveResource('Password').val();
		var cfpw = this.requestForEffectiveResource('ConfirmPassword').val();
		if (pw != cfpw)	{
			obj.requestForEffectiveResource('Error').html('Hai mật khẩu không giống nhau');
			return;
		}
		
		var token = this.token;
		if (token == undefined)	{
			token = this.getRequest().getParam('token');
		}
		
		this.onAjax('user-ajax', 'reset-password', 
				{'token': token, 'passwd': pw}, 'POST', {
						'onSuccess': function()	{
							var subject = SingletonFactory.getInstance(Subject);
							subject.notifyEvent('NotifyGlobal', 'Bạn đã thay đổi mật khẩu thành công');
							subject.notifyEvent('RequestRoute', new Request('Login'));
						},
						
						'onFailure': function(message)	{
							obj.requestForEffectiveResource('Error').html(message);	
						}
					});
	},
		
	run: function()	{
		this.getPortletPlaceholder().paintCanvas('');
		var token = this.getRequest().getParam('token', undefined);
		if (token == undefined)	{
			this.getPortletPlaceholder().paintCanvas(this.renderView('ErrorInvalidToken', {}));
		} else {
			var obj = this;
			this.onAjax('user-ajax', 'is-token-valid', {'token':token}, 'GET', {
				'onSuccess': function(ret)	{
					obj.token = token;
					obj.getPortletPlaceholder().paintCanvas(obj.render());
				},
				'onFailure': function(message)	{
					obj.getPortletPlaceholder().paintCanvas(obj.renderView('ErrorInvalidToken', {}));
				}
			});
		}
	},
	
	onEnd: function()	{
		this.unregisterObserver();
	}
}).implement(PortletInterface).implement(RenderInterface).implement(AjaxInterface).implement(ObserverInterface);
/**
 * 
 */
ExpertisePortlet = Class.extend({
	init: function()	{
		this.name = "ExpertisePortlet";
	},
	
	onBegin: function()	{
		this.model = {};
	},
	
	onReloadPage: function()	{
		this.run();
	},
	
	run: function()	{
		var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
		var obj = this;
		var id = this.getRequest().getParam('id');
		this.onAjax('ajax', 'get-all-expertises', {'id': id}, 'GET', 
				{'onSuccess': function(ret)	{
					var rsContexts = ret;
					for (var i=0;i<rsContexts.length;i++)	{
						var ctx = rsContexts[i];
						ctx.image = root+ctx.image;
						for(var j=0;j<ctx.content.length;j++)	{
							if (ctx.content[j].expertiseExplanation == undefined || ctx.content[j].expertiseExplanation == '')
								ctx.content[j].expertiseExplanation = '...';
							ctx.content[j].expertiseExplanation = obj.getLocalizedMessage('ExpertiseExplanation', ctx.content[j].expertiseExplanation, ctx.content[j].id, ctx.content[j].expertiseName);
						}
					}
		
					obj.model.expertiseTitle = "Kinh nghiệm";
					obj.model.expertiseContexts = rsContexts;
					obj.getPortletPlaceholder().paintCanvas(obj.render());
				}}, true, 300000);
	}
}).implement(PortletInterface).implement(RenderInterface).implement(AjaxInterface);

InterestedAreaPortlet = Class.extend({
	init: function()	{
		this.name = "InterestedAreaPortlet";
	},
	
	onBegin: function()	{
		this.model = {};
	},
	
	run: function()	{
		var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
		var obj = this;
		var id = this.getRequest().getParam('id');
		this.onAjax('ajax', 'get-all-interests', {'id': id}, 'GET', 
				{'onSuccess': function(ret)	{
					var rsContexts = ret;
					for (var i=0;i<rsContexts.length;i++)	{
						var ctx = rsContexts[i];
						ctx.image = root+ctx.image;
					}
				
					obj.model.interestTitle = "Lĩnh vực quan tâm";
					obj.model.interestContexts = rsContexts;
					obj.getPortletPlaceholder().paintCanvas(obj.render());
				}}, true, 300000);
	}
}).implement(PortletInterface).implement(RenderInterface).implement(AjaxInterface);

//PluginDebugPortlet = Class.extend({
//	init: function()	{
//		this.name = "PluginDebugPortlet";
//	},
//	
//	onBegin: function()	{
//		this.model = {};
//	},
//	
//	run: function()	{
//		var plgManager = SingletonFactory.getInstance(PluginManager);
//		this.model.plugins = new Array();
//		for(var i=0;i<plgManager.getPlugins().length;i++)	{
//			var plg = plgManager.getPlugins()[i];
//			this.model.plugins.push({'name': plg.getName(), 'loaded': plg.isLoaded()});
//		}
//		this.getPortletPlaceholder().drawToCanvas(this.render());
//	}
//}).implement(PortletInterface).implement(RenderInterface);
//
//PortletDebugPortlet = Class.extend({
//	init: function()	{
//		this.name = "PortletDebugPortlet";
//	},
//	
//	onBegin: function()	{
//		this.model = {};
//	},
//	
//	run: function()	{
//		var portletContainer = SingletonFactory.getInstance(PortletContainer);
//		this.model.portlets = new Array();
//		var portlets = portletContainer.getPortlets();
//		for(var i=0;i<portlets.length;i++)	{
//			var portlet = portlets[i];
//			if (portlet == undefined)	{
//				continue;
//			}
//			this.model.portlets.push({'name': portlet.portlet.getName(), 'active': portlet.active, 'position': portlet.position, 'loaded': portlet.loaded});
//		}
//		this.getPortletPlaceholder().drawToCanvas(this.render());
//	}
//}).implement(PortletInterface).implement(RenderInterface);

QuestionAskedPortlet = Class.extend({
	init: function()	{
		this.name = "QuestionAskedPortlet";
	},
	
	onBegin: function()	{
		this.model = {};
	},
	
	onReloadPage: function()	{
		this.run();
	},
	
	run: function()	{
		var obj = this;
		var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
		//FIXME: (Done) ProfileId must be retrieved from the request parameters
		var profileId = this.getRequest().getParam('id', undefined);
		
		this.onAjax('question', 'list-auth-question-by-target', {'target_id': profileId}, 'GET', 
				{'onSuccess': function(ret)	{
					obj.model.questionAskedTitle = "Các câu đã hỏi";
					obj.model.questions = ret;
					obj.getPortletPlaceholder().paintCanvas(obj.render());
				}});
	}
}).implement(PortletInterface).implement(RenderInterface).implement(AjaxInterface);

OwnAnswerPortlet = QuestionAskedPortlet.extend({
	init: function()	{
		this.name = "OwnAnswerPortlet";
		this.rows = 5;
		this.curPage = 1;
	},
	
	onReloadPage: function()	{
		this.run();
	},
	
	run: function()	{
		var obj = this;
		var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
		//FIXME: (Done) ProfileId must be retrieved from the request parameters
		var profileId = this.getRequest().getParam('id', undefined);

		var pagination = this.getRequest().getParam('pagination', 1);
		this.onAjax('answer', 'list-user-answer', {'id': profileId, 'from': (pagination-1)*this.rows, 'count': this.rows}, 'GET', 
				{'onSuccess': function(ret)	{
					obj.model.ownAnswerTitle = "Các câu đã trả lời";
					obj.model.answers = ret.answers;
					obj.getPortletPlaceholder().paintCanvas(obj.render());
					
					//build pagination
					var objParam = {};
					objParam.numDocs = ret.count;
					objParam.rows = obj.rows;
					objParam.curPage = pagination;
					objParam.request = obj.getRequest();
					objParam.placeholder = obj.requestForEffectiveResource('PaginationLink');
					var sbj = SingletonFactory.getInstance(Subject);
					sbj.notifyEvent("FetchPaginationLink", objParam);
				}});
	}
}).implement(PortletInterface).implement(RenderInterface).implement(AjaxInterface);

AskQuestionPortlet = Class.extend({
	init: function()	{
		this.name = "AskQuestionPortlet";
		this.selectedTopics = new Array();
	},
	
	onReloadPage: function()	{
		this.run();
	},
	
	onBegin: function()	{
		this.model = {};
		this.registerObserver();
	},
	
	run: function()	{
		//if the current profile is the current user's profile, hide everything!
		var properties = SingletonFactory.getInstance(Application).getSystemProperties();
		var loggedin = properties.get('user.login');
		if (loggedin == 1)	{
			var id = properties.get('user.id');
			var curID = this.getRequest().getParam('id');
			if (id == curID)	{
				this.getPortletPlaceholder().paintCanvas('');
				return;
			}
		}
		var currentProfileName = SingletonFactory.getInstance(Application).getSystemProperties().get('profile.current.name');
		this.model.optionalMsg = this.getLocalizedText("OptionalMessage");
		this.model.optionalDetailMsg = this.getLocalizedText("OptionalDetailMessage");
//		if (currentProfileName == undefined)	{
			this.model.askMsg = this.getLocalizedText("AskMessageMissingTarget");
//		} else {
//			this.model.askMsg = this.getLocalizedMessage("AskMessage", currentProfileName);
//		}
		this.getPortletPlaceholder().paintCanvas(this.render());
	},
	
	onEnd: function()	{
		this.unregisterObserver();
	},
	
	onAskTextBoxFocus: function(eventData)	{
		var input = this.requestForEffectiveResource('TextBox');
		if ($(input).hasClass('questionTextBox-NonFocus'))	{
			$(input).removeClass('questionTextBox-NonFocus');
			$(input).val('');
		}
		this.requestForEffectiveResource("Extended").show();
	},
	
	onAskTextBoxBlur: function()	{
		var input = this.requestForEffectiveResource('TextBox');
		if ($(input).val().trim() == '')	{
			$(input).addClass('questionTextBox-NonFocus');
			$(input).val('Mời bạn nhập câu hỏi');
		}
	},
	
	onAskQuestionAutocompleteFetched: function(eventData)	{
		var addTopic = this.requestForEffectiveResource("AddTopic");
		$(addTopic).show();
	},
	
	// FIXME:
	onAskQuestionTopicFocus: function(eventData)	{
		var ui = eventData.ui;
		var addTopicInputBox = this.requestForEffectiveResource("AddTopicInputBox");
		$(addTopicInputBox).val(ui.item.label);
	},
	
	onAskQuestionTopicSelect: function(eventData)	{
		var ui = eventData.ui;
		var i = 0;
		var txt = ui.item.label;
		var value = ui.item.value;
		
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent('AskQuestionPortletAppend', {'txt': txt, 'value': value});
	},
	
	onAskQuestionPortletAppend: function(eventData)	{
		var txt = eventData.txt;
		var value = eventData.value;
		
		var topicContainer = this.requestForEffectiveResource("AddTopicContainer");
		var addTopicInputBox = this.requestForEffectiveResource("AddTopicInputBox");
		var selectedTopics = new Array();
		this.selectedTopics = selectedTopics;
		
		for( i=0; i<selectedTopics.length;i++ ){
			if(selectedTopics[i] === value){
				return;
			}
		}
		var textToken = $("<label>").text(txt).addClass("tokenContent");
		selectedTopics.push(value);
		
		// UI ONLY
		var span = $("<span>").addClass("uiToken").append(textToken);
		var a = $("<input>").addClass("btnStl").addClass("delToken").bind("click",function(event){
				var start = 0;
				for( start=0; start<selectedTopics.length; start++ ){
					if(selectedTopics[start] === value){
						break;
					}
				}
				selectedTopics.splice(start, 1);
				$(event.target).parent().remove();
			}).val("X").css("text-align","center").appendTo(span);
		topicContainer.append(span);
	},
	
	onAskQuestionPortletAddTopic: function(eventData){
//		if (this.autocompleteGenerated == true)
//			return;
		this.autocompleteGenerated = true;
		var addTopicInputBox = this.requestForEffectiveResource("AddTopicInputBox"); 
		//FIXME: data should be loaded only once !addTopicInputBox
		var eventData = {};
		eventData.focusCallback = "AskQuestionTopicFocus";
		eventData.selectCallback = "AskQuestionTopicSelect";
		eventData.autocompleteObject = addTopicInputBox;
		eventData.autocompleteSource = "catchword/autocomplete-all-catchwords";
		eventData.fetchSourceCallback = "AskQuestionAutocompleteFetched";
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent('NeedAutocomplete', eventData);
	},
	
	onAskProfileButtonClick: function(eventData)	{
		var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
		var question = this.requestForEffectiveResource("TextBox").val();
		var extended = this.requestForEffectiveResource("TextAreaExtended").val();
		var obj = this;
		//FIXME: (Done) profile ID must be retrieved from the request parameters
		obj.requestForEffectiveResource("QuestionInfo").html("");
		obj.requestForEffectiveResource("QuestionError").html("");
		var profileId = this.getRequest().getParam('id', 1);
		var selectedTopics = null;
		if(this.selectedTopics.length > 0){
			selectedTopics = new Array();
			for( var i=0; i<this.selectedTopics.length; i++ ){
				selectedTopics.push({"catchword_id":this.selectedTopics[i],"position":0}); 
			}
		}
		this.onAjax('question', 'add-unauth-question', {'target_id': profileId, 'title': question, 'content': extended, 'catch': selectedTopics}, 'POST', 
				{'onSuccess': function(ret)	{
					obj.requestForEffectiveResource("TextBox").val("");
					obj.requestForEffectiveResource("TextAreaExtended").val("");
					obj.requestForEffectiveResource("Extended").hide();
					obj.requestForEffectiveResource("AddTopic").hide();
					obj.requestForEffectiveResource("AddTopicContainer").html("");
					obj.selectedTopics = new Array();
					obj.requestForEffectiveResource("QuestionInfo").html(obj.getLocalizedText("AskSuccess"));
					},
				'onFailure': function(message)	{
						obj.requestForEffectiveResource("QuestionError").html(obj.getLocalizedText("AskError"));
					}});
	}
}).implement(PortletInterface).implement(RenderInterface).implement(ObserverInterface).implement(AjaxInterface);

AskNonTargetQuestionPortlet = Class.extend({
	init: function()	{
		this.name = "AskNonTargetQuestionPortlet";
		this.selectedTopics = new Array();
		this.usingFacebox = false;
	},
	
	requestForEffectiveResource: function(targetName){
		if(this.usingFacebox){
			//console.log('in request: '+targetName);
			//console.log($("#"+this.name+"-"+targetName));
			return $("#"+this.name+"-"+targetName);
		}else{
			return this._super.requestForEffectiveResource(targetName);
		}
	},
	
	onMakeNewQuestion: function(eventData)	{
		this.showPortlet(eventData);
	},
	
	showPortlet: function(eventData){
		//console.log("shown");
		var loggedIn = SingletonFactory.getInstance(Application).getSystemProperties().get('user.login');
		if (loggedIn != 1)	{
			var subject = SingletonFactory.getInstance(Subject);
			subject.notifyEvent("NeedLogin", eventData);
		} else {
			this.doShowPortlet(eventData);
		}
	},
	
	onLoginSuccess: function(eventData)	{
//		this.doShowPortlet(eventData);
	},
	
	// Mar21
	doShowPortlet: function(eventData)	{
		var app = SingletonFactory.getInstance(Application);
		var subject = SingletonFactory.getInstance(Subject);
		var logined = app.getSystemProperties().get("user.login");
		// FIXME: check log in !
		this.usingFacebox = true;
		this.model.optionalMsg = $("#"+this.name+"-TextOptionalMessage").html();
		this.model.optionalDetailMsg = $("#"+this.name+"-TextOptionalDetailMessage").html();
		this.model.askMsg = $("#"+this.name+"-TextAskMessage").html();
		this.model.question = eventData.question;
		$.facebox(this.render());
		$('#AskNonTargetQuestionPortlet-TextBox').focus();
		
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent('AskNonTargetQuestionPortletFetchAutocomplete');
		
		$('#facebox').show();
//		var sbj = SingletonFactory.getInstance(Subject);
//		sbj.notifyEvent('ExpandTextArea', {'target': this.requestForEffectiveResource('TextAreaExtended')});
	},
	
	onAskNonTargetQuestionPortletFetchAutocomplete: function()	{
		var addTopicInputBox = this.requestForEffectiveResource("AddTopicInputBox"); 
		//FIXME: data should be loaded only once !addTopicInputBox
		var eventData = {};
		eventData.focusCallback = "AskNonTargetQuestionTopicFocus";
		eventData.selectCallback = "AskNonTargetQuestionTopicSelect";
		eventData.autocompleteObject = addTopicInputBox;
		eventData.autocompleteSource = "catchword/autocomplete-all-catchwords";
		eventData.fetchSourceCallback = "AskNonTargetQuestionAutocompleteFetched";
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent('NeedAutocomplete', eventData);
	},
	
	onBegin: function()	{
		this.model = {};
		this.registerObserver();
	},
	
	run: function()	{
		this.model.optionalMsg = this.getLocalizedText("OptionalMessage");
		this.model.optionalDetailMsg = this.getLocalizedText("OptionalDetailMessage");
		this.model.askMsg = this.getLocalizedText("AskMessage");
		this.getPortletPlaceholder().drawToCanvas(this.render());
	},
	
	onEnd: function()	{
		this.unregisterObserver();
	},
	
	onAskNonTargetQuestionAutocompleteFetched: function(eventData)	{
		
	},
	
	onAskNonTargetQuestionTopicFocus: function(eventData)	{
		//console.log("onAskNonTargetQuestionTopicFocus");
		var ui = eventData.ui;
		var addTopicInputBox = this.requestForEffectiveResource("AddTopicInputBox");
		$(addTopicInputBox).val(ui.item.label);
	},
	
	
	// Chọn topic
	onAskNonTargetQuestionTopicSelect: function(eventData)	{
		var ui = eventData.ui;
		var i = 0;
		var txt = ui.item.label;
		var value = $("a[catch='"+escape(txt)+"']").attr("catch_id");
		
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent('AskNonTargetQuestionPortletAppend', {'txt': txt, 'value': value});
	},
	
	onAskNonTargetQuestionPortletAppend: function(eventData)	{
		var txt = eventData.txt;
		var value = eventData.value;
		var topicContainer = this.requestForEffectiveResource("AddTopicContainer");
		var addTopicInputBox = this.requestForEffectiveResource("AddTopicInputBox");
		if (this.selectedTopics == undefined)
			this.selectedTopics = Array();
		for( i=0; i<this.selectedTopics.length;i++ ){
			if(this.selectedTopics[i] === value){
				return;
			}
		}
		var textToken = $("<label class='tokenContent'>"+txt+"</label>");
		this.selectedTopics.push(value);
		
		// UI ONLY
		selectedTopics = this.selectedTopics;
		var span = $("<span>").addClass("uiToken").append(textToken);
		var a = $("<input>").addClass("btnStl").addClass("delToken").bind("click",function(event){
				var start = 0;
				for( start=0; start<selectedTopics.length; start++ ){
					if(selectedTopics[start] === value){
						break;
					}
				}
				selectedTopics.splice(start, 1);
				$(event.target).parent().remove();
			}).val("X").css("text-align","center").appendTo(span);
		topicContainer.append(span);
	},
	
	onAskNonTargetQuestionPortletAddTopic: function(eventData){
		var addTopic = this.requestForEffectiveResource("AddTopic");
		$(addTopic).show();
//		if (this.autocompleteGenerated == true)
//			return;
		this.autocompleteGenerated = true;
		var addTopicInputBox = this.requestForEffectiveResource("AddTopicInputBox"); 
		
		//FIXME: data should be loaded only once !addTopicInputBox
		var eventData = {};
		eventData.focusCallback = "AskNonTargetQuestionTopicFocus";
		eventData.selectCallback = "AskNonTargetQuestionTopicSelect";
		eventData.autocompleteObject = addTopicInputBox;
		eventData.autocompleteSource = "catchword/autocomplete-all-catchwords";
		eventData.fetchSourceCallback = "AskNonTargetQuestionAutocompleteFetched";
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent('NeedAutocomplete', eventData);
		//console.log('event called');
	},
	
	onAskNonTargetTextBoxFocus: function(eventData)	{
		//console.log("onAskNonTargetTextBoxFocus");
		this.requestForEffectiveResource("Extended").show();
	},
	
	onAskNonTargetButtonClick: function(eventData)	{
		//console.log("onAskNonTargetButtonClick");
		var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
		var question = this.requestForEffectiveResource("TextBox").val();
		var extended = this.requestForEffectiveResource("TextAreaExtended").val();
		var obj = this;
		obj.requestForEffectiveResource("QuestionInfo").html("");
		obj.requestForEffectiveResource("QuestionError").html("");
		var selectedTopics = null;
		if(this.selectedTopics.length > 0){
			selectedTopics = new Array();
			for( var i=0; i<this.selectedTopics.length; i++ ){
				//console.log(this.selectedTopics[i]);
				selectedTopics.push({"catchword_id":this.selectedTopics[i],"position":0}); 
			}
		}
		this.onAjax('question', 'add-unauth-question', {'title': question, 'content': extended, 'catch': selectedTopics}, 'POST', 
				{'onSuccess': function(ret)	{
					this.selectedTopics = Array();
//					obj.requestForEffectiveResource("TextBox").val("");
//					obj.requestForEffectiveResource("TextAreaExtended").val("");
//					obj.requestForEffectiveResource("Extended").hide();
////					obj.requestForEffectiveResource("AddTopic").hide();
//					obj.requestForEffectiveResource("AddTopicContainer").html("");
//					obj.selectedTopics = new Array();
//					obj.requestForEffectiveResource("QuestionInfo").html(obj.getLocalizedText("AskSuccess"));
					$.facebox.close();
					var sbj = SingletonFactory.getInstance(Subject);
					sbj.notifyEvent("NotifyGlobal", obj.getLocalizedText("AskSuccess"));
					},
				'onFailure': function(message)	{
						obj.requestForEffectiveResource("QuestionError").html(obj.getLocalizedText("AskError"));
					}});
	}
}).implement(PortletInterface).implement(RenderInterface).implement(ObserverInterface).implement(AjaxInterface);

QuestionAskingPortlet = Class.extend({
	init: function()	{
		this.name = "QuestionAskingPortlet";
	},
	
	onBegin: function()	{
		this.model = {};
	},
	
	onReloadPage: function()	{
		this.run();
	},
	
	run: function()	{
		var obj = this;
		var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
		//FIXME: (Done) ProfileId must be retrieved from the request parameters
		var profileId = this.getRequest().getParam('id', undefined);
		this.onAjax('question', 'list-auth-question-by-user', {'user_id': profileId}, 'GET', 
				{'onSuccess': function(ret)	{
					obj.model.questionAskedTitle = "Các câu đang hỏi";
					obj.model.questions = ret;
					obj.getPortletPlaceholder().paintCanvas(obj.render());
				}});
	}
}).implement(PortletInterface).implement(RenderInterface).implement(AjaxInterface);

QuestionPendingPortlet = QuestionAskingPortlet.extend({
	init: function()	{
		this.name = "QuestionPendingPortlet";
	},
	
	run: function()	{
		var obj = this;
		var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
		var pendingQuestions = Array();
		var cached = SingletonFactory.getInstance(Application).getSystemProperties().get("memcached.pendingQuestions");
		this.onAjax('question', 'list-user-pending-question', {}, 'GET', 
				{'onSuccess': function(ret)	{
					obj.model.questionPendingTitle = "Các câu hỏi đang chờ duyệt";
					obj.model.questionPendingDescription = obj.getLocalizedText('QuestionPendingDescription');
					obj.model.questions = Array();
					for (var i=0;i<ret.length;i++)	{
						var r = ret[i];
						pendingQuestions[r.id] = r;
						if (r.target_name == undefined)
							r.target_name = "";
						obj.model.questions.push(obj.getLocalizedMessage('QuestionSummary', r.target_name, r.title, $.timeFormat(r.created_date), r.id, r.id));
					}
					obj.getPortletPlaceholder().paintCanvas(obj.render());
					SingletonFactory.getInstance(Application).getSystemProperties().set("memcached.pendingQuestions",pendingQuestions);
				}});
	}
}).implement(PortletInterface).implement(RenderInterface).implement(AjaxInterface);

QuestionClickPlugin = Class.extend({
	init: function()	{
		this.name = "QuestionClick";
	},
	
	onQuestionSummaryClick: function(eventData)	{
		Request.setProactive(true);
		var request = new Request("Question", undefined, {'qid': eventData});
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent("RequestRoute", request);
	}
}).implement(PluginInterface);

AutocompletePlugin = Class.extend({
	init: function()	{
		this.name = "AutocompletePlugin"
	},
	
	onNeedAutocomplete: function(eventData)	{
		//console.log('autocomplete');
		var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
		var subject = SingletonFactory.getInstance(Subject);
		var url = root+eventData.autocompleteSource;
		var suggestions = Array();
		var obj = eventData.autocompleteObject;
		
		$.getJSON(url, function(data) {
			$.each(data['result'], function(i, val){	
				var str = val.label + "##" + val.id;
				suggestions.push({label:str,value:val.label});
			});
			
			if (eventData.fetchSourceCallback != undefined)
				subject.notifyEvent(eventData.fetchSourceCallback);
			$(obj).autocomplete({
				source: suggestions,
				focus:  function(e,ui){
					if (eventData.focusCallback != undefined)
						subject.notifyEvent(eventData.focusCallback, {'ui':ui});
				},
				select: function(e,ui){
					if (eventData.selectCallback != undefined)
						subject.notifyEvent(eventData.selectCallback, {'ui':ui});
				},
				result: function(e, ui)	{
					if (eventData.resultCallback != undefined)
						subject.notifyEvent(eventData.resultCallback, {'ui':ui});
				}
			});
		});
	}
}).implement(PluginInterface);

BriefInfoPortlet = Class.extend({
	init: function()	{
		this.name = "BriefInfoPortlet";
	},
	
	onReloadPage: function()	{
		this.run();
	},
	
	run: function()	{
		this.model = {};
		var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
		var obj = this;
		var props = SingletonFactory.getInstance(Application).getSystemProperties();
		var id = this.getRequest().getParam('id');
		this.onAjax('user-ajax', 'get-brief-info', {'id': id}, 'GET', {
			'onSuccess': function(ret)	{
			
				// basic
				var avatar = ret.avatar;
				if (avatar == "" || avatar == undefined)	{
					avatar = "index.jpg";
				}
				obj.model.page = obj.getRequest().getParam('page');
				obj.model.id = id ? id: props.get('user.id');
				obj.model.name = ret.name;
				obj.model.avatar = "avatar/"+avatar;
				
				// statistic
				obj.model.answerCount = ret.answerCount;
				obj.model.questionCount = ret.questionCount;
				
				// interests
			
				obj.model.interestTitle = "Lĩnh vực quan tâm";
				obj.model.interestContexts = ret.interests;
				
				// catches
				
				obj.model.expertiseTitle = "Kinh nghiệm";
				obj.model.expertiseContexts = ret.catches;
				
				obj.getPortletPlaceholder().paintCanvas(obj.render());
			}
		});
	}
}).implement(PortletInterface).implement(RenderInterface).implement(AjaxInterface);

AvatarEditPlugin = Class.extend({
	init: function()	{
		this.name = "AvatarEditPlugin";
	},
	
	onReloadPlugin: function()	{
		this.renderAvatar();
	},
	
	onAvatarUploadDone: function()	{
		var f = $('#avatar_upload_target');
		var ret = f.document.getElementsByTagName("body")[0].innerHTML;
		var ret = $(f).html();
		if (ret == "" || ret == undefined)	{
			return;
		}
	},
	
	onAvatarInputChange: function()	{
		$('#AvatarUploaderContainer').submit();
	},
	
	renderAvatar: function()	{
		var obj = this;
		$('.extension-point[extensionName="avatar"]').each(function(index, value)	{
			if ($(value).find('div[flag="AvatarUploader"]').length>0)
				return;
			var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
			$(value).append(tmpl('AvatarUploader', {'root': root}));
			$('#AvatarUploaderContainer').submit(function() {
				var fr = $('#avatar-upload-frame');
				$(fr).one('load', function() {
					var response = fr.contents().find('body').html();
					$('AvatarUploaderContainer').find('input[type="submit"]').attr('disabled', '');
			    	var ret = $.parseJSON(response);
			    	$(value).find('#AvatarUploaderErrorPlaceholder').html('');
			    	if (ret.result == "error")	{
			    		errors = {};
			    		errors.errors = ret.message; 
			    		$(value).find('#AvatarUploaderErrorPlaceholder').html(tmpl('AvatarUploaderError', errors));
			    	} else {
		    			$('#AvatarPortlet .avatar-block img').attr('src', 'avatar/'+ret.result);
		    			var subject = SingletonFactory.getInstance(Subject);
		    			subject.notifyEvent('NotifyGlobal', 'Bạn đã thay đổi avatar thành công. Nếu ảnh chưa hiện ra, hãy ấn F5 để thấy sự thay đổi');
			    	}
				});
			});
		});
	},
	
	onHtmlUpdated: function()	{
		this.renderAvatar();
	}
}).implement(PluginInterface);

CredentialsEditPlugin = Class.extend({
	init: function()	{
		this.name = "CredentialsEditPlugin";
	},

	renderCredentialsLink: function()	{
		var obj = this;
		$('.extension-point[extensionName="usercpedit"]').each(function(index, value)	{
			if ($(value).find('div[flag="UserCPEdit"]').length>0)
				return;
			$(value).append(tmpl('UserCP', {}));
		});
	},
	
	onProfileExpertiseEditShow: function()	{
		$.facebox(tmpl('UserCP-EditExpertise', {}));
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent('RenderExpertiseEditor', {namespace: 'UserCP', placeholder: $('#facebox #UserCP-ExpertisePlaceholder')});
	},
	
	onSubmitExpertiseProfileButtonClick: function(eventData)	{
		var target = eventData.target;
		var parent = $(target).parents('#UserCP-ViewPlaceholder:first');
		var expToSent = Array();
		var container = $(parent).find('#UserCP-ListExpertise .tokenContainer');
		$(container).find('label.lblToken').each(function(index, value)	{
			var id = $(value).attr('eid');
			expToSent.push(id);
		});
		
		var intToSent = Array();
		var container = $(parent).find('#UserCP-ListInterestedArea .tokenContainer');
		$(container).find('label.lblToken').each(function(index, value)	{
			var id = $(value).attr('eid');
			intToSent.push(id);
		});
		var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
		intToSent = $.toJSON(intToSent);
		expToSent = $.toJSON(expToSent);
		var obj = this;
		this.onAjax('ajax', 'add-expertise', {'experts': expToSent, 'interests': intToSent}, 'POST', 
				{'onSuccess': function(ret)	{
					obj.finishSubmitting();
				}});
	},
	
	finishSubmitting: function()	{
		$.facebox.close();
	},
	
	onHtmlUpdated: function()	{
		this.renderCredentialsLink();
	}
}).implement(PluginInterface).implement(AjaxInterface);

ProfileNameEditPlugin = Class.extend({
	init: function()	{
		this.name = "ProfileNameEditPlugin";
	},
	
	saveData: function(event)	{
		var target = event.target;
		var newValue = $(target).val().trim();
		var oldValue = $(target).attr('oldValue');
		if (newValue == "")	{
			newValue = oldValue;
		}
		$(target).parent().removeAttr('editing');
		$(target).parent().html('<a>'+newValue+'</a>');
		if (oldValue != newValue)	{
			this.onAjax('user-ajax', 'edit-name', {'name': newValue}, 'POST', {});
		}
	},
	
	onProfileEditOnBlur: function(event)	{
		this.saveData(event);
	},
	
	onProfileEditOnKeyup: function(event)	{
		var keycode = event.keyCode;
		if (keycode == 13)	{
			this.saveData(event);
		}
	},
	
	onProfileNameEditClick: function(event)	{
		var target = event.target;
		var editTarget = $(target).parent().parent().find('.profile-name');
		if ($(editTarget).attr('editing') == 'editing')
			return;
		var old = $(editTarget).find('a').html();
		$(editTarget).attr('editing', 'editing');
		$(editTarget).html('<input oldValue="'+old+'" onkeyup="generateEvent(&apos;ProfileEditOnKeyup&apos;, event)" onblur="generateEvent(&apos;ProfileEditOnBlur&apos;, event)" value="'+old+'">');
		$(editTarget).find('input').focus();
	},

	renderEditLink: function()	{
		var obj = this;
		$('.extension-point[extensionName="ProfileName"]').each(function(index, value)	{
			if ($(value).find('div[flag="ProfileNameEdit"]').length>0)
				return;
			$(value).append(tmpl('ProfileNameEdit', {}));
		});
	},
	
	onHtmlUpdated: function()	{
		this.renderEditLink();
	}
}).implement(PluginInterface).implement(AjaxInterface);

ShowTopicCreatePopupPlugin = Class.extend({
	init: function()	{
		this.name = "ShowTopicCreatePopupPlugin";
	},
	
	onShowTopicCreatePopup: function(eventData)	{
		var cb = eventData.callback;
		var cmcb = eventData.commitcallback;
		var w = 600;
		var h = 400;
		var left = (screen.width/2)-(w/2);
		var top = (screen.height/2)-(h/2);
		window.open('#page/TopicCreatePagePopup/callback/'+cb+'/commit-callback/'+cmcb, 'topicCreateWindow', "status = 0, height = "+h+", width = "+w+", resizable = 1, left = "+left+", top = "+top);
	}
}).implement(PluginInterface);
/**
 * 
 */
ProfileInformationPortlet = Class.extend({
	init: function()	{
		this.subject = SingletonFactory.getInstance(Subject);
		this.name = 'ProfileInformationPortlet';
		this.profile_id = undefined;
	},
	
	onReloadPage: function()	{
		//console.log('page is reloaded');
		this.run();
	},
	
	onBegin: function()	{
		this.registerObserver();
		this.buildTemplate();
	},
	
	run: function()	{
		var root = SingletonFactory.getInstance(Application).getSystemProperties().get('host.root');
		var profileId = this.getRequest().getParam('id', undefined);
		var obj = this;
		this.onAjax('ajax', 'get-profile-detail', {'id':profileId}, 'GET', 
				{'onSuccess': function(ret)	{
					obj.onGetProfileDetailSuccess(ret);
				},
				'onFailure': function(message)	{
//					var subject = SingletonFactory.getInstance(Subject);
//					var request = new Request("ErrorPage","",{"code":"888", "msg":"Lỗi","content":"Không tìm thấy profile"}); 
//					subject.notifyEvent('RequestRoute', request);
					//obj.getPortletPlaceholder().paintCanvas('Profile không tồn tại');
					
					//redirect to error page
					var request = new Request('ErrorPage', undefined, {'code':404});
					var subject = SingletonFactory.getInstance(Subject);
					subject.notifyEvent('RequestRoute', request);
				}}, true, 1800000);
	},
	
	onGetProfileDetailSuccess: function(ret)	{
		this.getPortletPlaceholder().paintCanvas(this.requestForResource('ViewData').html());
		var data = ret.data;
		this.profile_id = ret.profile_id;
		var stack = Array();
		for(var i=0;i<data.length;i++)	{
			data[i].depth = 0;
			stack.push(data[i]);
		}
		if (data.length>0)	{	
			while(stack.length > 0)	{
				var current = stack.pop();
				this.processNode(current);
				if (typeof current.children != 'undefined')	{
					for(var i=0;i<current.children.length;i++)	{
						var child = current.children[i];
						child.depth = current.depth+1;
						stack.push(child);
					}
				}
			}
			this.finishRendering();
		}
	},
	
	finishRendering: function()	{
		var id = this.getRequest().getParam('id');
		if (id == undefined)	{
			this.getPortletPlaceholder().getCanvas().access().find('h1').hide();
		}
		this.subject.notifyEvent("NeedFormatting");
	},
	
	processNode: function(current)	{
		if (current.keyword == 'full_name')	{
//			this.requestForEffectiveResource('ProfileName').html(current.content);
//			SingletonFactory.getInstance(Application).getSystemProperties().set('profile.current.name', current.content);
		} else {
			this.renderPlaceholder(current);
		}
	},
	
	buildTemplate: function()	{
		var rootNode = this.requestForResource('ProfileStructure');
		var placeholder = this.requestForResource('ProfileMainContent');
		this.subject.notifyEvent('BuildProfileTemplate', {'id': this.name, 'root':rootNode, 'placeholder': placeholder});
	},
	
	onShareButtonClick: function(e)	{
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent('NeedLogin');
	},
	
	onLoginSuccess: function()	{
		this.subject.notifyEvent('NeedToggleRelationship');
	},
	
	onNeedToggleRelationship: function()	{
		this.toggle();
	},
	
	toggle: function()	{
		var properties = SingletonFactory.getInstance(Application).getSystemProperties();
		var id = properties.get('user.id');
		//FIXME: (Done) profileId must be retrieved in request parameter 
		var root = properties.get('host.root');
		$('.relationship').slideToggle();
		var obj = this;
		this.onAjax('ajax', 'compare-relationship', {'profile-id':this.profile_id}, 'POST', 
				{'onSuccess': function(ret)	{
					obj.onCompareRelationshipSuccess(ret);
				}});
	},
	
	onCompareRelationshipSuccess: function(ret)	{
		var partial = {};
		partial.result = Array();
		for(i=0;i<ret.length;i++)
		{
			partial.result.push(ret[i]);
		}
		var level = "";
		var mark = (ret.length / 7).toFixed(2);
		if (mark < 0.4) level = this.getLocalizedText('LowRelation');
		else if (mark < 0.65) level = this.getLocalizedText('NormalRelation');
			else if (mark < 0.75) level = this.getLocalizedText('FairRelation');
				else level = this.getLocalizedText('HighRelation');
		var str = this.renderView("ProfileRelationPartial", partial);
		var number = ret.length || 0;
		var summary = this.getLocalizedMessage('RelationSummary', number, level);
		dataObj = {};
		dataObj.content = str;
		dataObj.summary = summary;
		var str = this.renderView("ProfileShareInfo", dataObj);
		$('.relationship').html(str);
	},

	renderPlaceholder: function(current)	{
		this.subject.notifyEvent('RenderPlaceholder', {'node': current, 'callback': 'RenderingDone', 'id': this.name, 'state':'View'});
	},
	
	onRenderingDone: function(eventData)	{
		var html = eventData.html;
		var current = eventData.node;
		var parentChildrenContainerID = current.p_keyword+'Children'+current.p_oid;
		if ($(this.requestForEffectiveResource(parentChildrenContainerID)).length == 0 )	{
//			 //console.log('the children container for '+current.keyword+' not exists('+parentChildrenContainerID+')');
			this.insertAfterPrototype(html, current);
		}
		// otherwise, create new inside the parent's children container
		else {
//			 //console.log('the children container for '+current.keyword+' exists');
			//find the most appropriate sibling
			var siblings = this.requestForMatchingEffectiveResource(parentChildrenContainerID, "[rootname='"+current.keyword+"']:first");
			if (siblings != undefined && siblings.length > 0)	{
//				//console.log('found sibling: '+current.keyword);
				$(html).insertAfter($(siblings));
			} else {
				this.requestForEffectiveResource(parentChildrenContainerID).append(html);
			}
		}
	},
	
	insertAfterPrototype: function(html, current)	{
		$(html).insertAfter(this.requestForEffectiveResource(current.keyword+'Prototype'));
	},
	
	onEnd: function()	{
		this.unregisterObserver();
	}
}).implement(PortletInterface).implement(RenderInterface).implement(ObserverInterface).implement(AjaxInterface);

ProfileTemplatePlugin = Class.extend({
	init: function()	{
		this.name = "ProfileTemplatePlugin";
		this.nodeTypes = Array();
	},
	
	onBuildProfileTemplate: function(eventData)	{
		var id = eventData.id;
		var rootNode = eventData.root;
		var placeholder = eventData.placeholder;
		
		this.nodeTypes[id] = Array();
		var stack = Array();
		rootNode.depth = 0;
		rootNode.parent = undefined;
		stack.push(rootNode);
		var partialRootObj = {};
		partialRootObj.namespace = id;
		partialRootObj.name = $(rootNode).attr('name');
		partialRootObj.type = $(rootNode).attr('type');
		partialRootObj.params = $(rootNode).attr('params');
		var html = tmpl('TemplatePartial', partialRootObj);
		$(placeholder).html(html);
		while (stack.length>0)	{
			rootNode = stack.pop();
			this.storeNodeDetail(id, rootNode);
			var childrenNode = $(rootNode).children();
			if (rootNode.parent != undefined)	{
				this.buildPrototype(id, rootNode.parent, rootNode);
			}
			for(var i=0;i<childrenNode.length;i++)	{
				var childNode = childrenNode[i];
				childNode.parent = rootNode;
				childNode.depth = rootNode.depth+1;
				stack.push(childNode);
			}
		}
	},
	
	buildPrototype: function(id, rootNode, childNode)	{
		var partialObj = {};
		partialObj.name = $(childNode).attr('name');
		partialObj.type = $(childNode).attr('type');
		partialObj.params = $(childNode).attr('params');
		partialObj.namespace = id;
		var partial = tmpl('TemplatePartial', partialObj);
		$('div[name="'+$(rootNode).attr('name')+'_container_children"]').append(partial);
	},
	
	storeNodeDetail: function(id, rootNode)	{
		var name = $(rootNode).attr('name');
		this.nodeTypes[id][name] = {};
		this.nodeTypes[id][name].type = $(rootNode).attr('type');
		this.nodeTypes[id][name].params = $(rootNode).attr('params');
		this.nodeTypes[id][name].value = $(rootNode).attr('value');
		this.nodeTypes[id][name].parent = rootNode.parent;
		this.nodeTypes[id][name].depth = rootNode.depth-1;
		this.nodeTypes[id][name].singleton = $(rootNode).attr('singleton');
	},
	
	onRenderPlaceholder: function(eventData)	{
		var current = eventData.node;
		var callback = eventData.callback;
		var state = eventData.state;
		var id = eventData.id;
		// build the placeholder
		var obj = {};
		obj.id = current.oid;
		obj.name = current.keyword;
		if (this.nodeTypes[id][obj.name] != undefined)	{
			obj.type = this.nodeTypes[id][obj.name].type;
			obj.params = this.nodeTypes[id][obj.name].params;
		}
		if (typeof obj.type == 'undefined')	{
			// //console.log('object of type '+obj.name+' is undefined');
			return;
		}
		this.nodeTypes[id][obj.name].existed = true;
		var objdata = {};
		objdata.type = obj.type;
		objdata.depth = current.depth;
		objdata.keyword = this.nodeTypes[id][obj.name].value;
		objdata.content = current.content;
		objdata.name = current.keyword;
		objdata.params = obj.params;
		objdata.state = state;
		// //console.log('will create '+obj.type);
		obj.content = tmpl('UnformattedPlaceholder', objdata);
		obj.namespace = id;
		var html = tmpl('ProfilePartial', obj);
		// if the parent is undefined then create new after the prototype
		var parent = this.nodeTypes[id][obj.name].parent;
		if (current.p_keyword != $(parent).attr('name'))	{
			// //console.log('conflict between server and client profile structure
			// ('+current.p_keyword+' and '+$(parent).attr('name')+')');
			current.p_keyword = $(parent).attr('name');
		}
		var subject = SingletonFactory.getInstance(Subject);
		subject.notifyEvent(callback, {'node': current, 'html':html});
	},
	
	onBuildMockupNode: function(eventData)	{
		var name = eventData.nodeName;
		var ancestor = eventData.nodeBefore;
		var id = eventData.id;
		var node = this.nodeTypes[id][name];
		//build the mockup node
		var html = this.buildMockupNode(node);
		$("<div class='container'>"+html+"</div>").insertAfter($(ancestor));
	},
	
	buildMockupNode: function(node)	{
		var obj = {};
		obj.depth = node.depth;
		obj.params = node.params;
		obj.type = node.type;
		obj.name = node.name;
		obj.keyword = node.value;
		obj.content = node.value;
		return tmpl('AddNewPlaceholder', obj);
	},	
	
	onDisplayRemainingNodes: function(eventData)	{
		this.displayRemainingNodes(eventData.id);
	},

	buildNodeFromObject: function(namespace, node, id, partialView)	{
		var obj = {};
		obj.id = id;
		obj.name = node.name;
		obj.type = node.type;
		obj.params = node.params;
		var objdata = {};
		objdata.type = node.type;
		objdata.depth = node.depth;
		objdata.keyword = node.value;
		objdata.content = node.value;
		objdata.name = node.name;
		objdata.params = node.params;
		objdata.state = "Edit";
		obj.content = tmpl(partialView, objdata);
		obj.namespace = namespace;
		var html = tmpl('ProfilePartial', obj);
		return html;
	},
	
	displayRemainingNodes: function(id)	{
		for(var name in this.nodeTypes[id])	{
			this.displayRemainingNode(id, name);
		}
		$('div[rootName]').attr('added', 'true');
	},
	
	displayRemainingNode: function(id, name)	{
		var obj = this.nodeTypes[id][name];
		if (obj.singleton !== "true" || obj.existed != true)	{
			obj.name = name;
			var html = "";
			if (obj.singleton !== "true")
				html = this.buildNodeFromObject(id, obj, 'AddNew','AddNewPlaceholder');
			else 	{
				html = this.buildNodeFromObject(id, obj, '', 'UnformattedPlaceholder-Edit');
			}
			var parent = $(obj.parent).attr('name');
			var parentNode = $('div[rootName="'+parent+'"]');
//			//console.log('finding parent '+'div[rootName="'+parent+'"]');
			$(parentNode).each(function(index, value)	{
				if ($(value).attr('added') == 'true')	{
					return;
				}
//				//console.log('found');
				if ($(value).find('div[rootName="'+name+'"]').length > 0)	{
					//existing
					$(html).insertAfter($(value).find('div[rootName="'+name+'"]').last());
				} else {
					$(value).children('.children_container').append(html);
				}
			});
		}
	}
}).implement(PluginInterface);
/**
 * 
 */
ProfileEditPortlet = ProfileInformationPortlet.extend({
	init: function()	{
		this._super();
		this.name = 'ProfileEditPortlet';
		var usedId = 0;
	},
	
	processNode: function(node)	{
		this.renderPlaceholder(node);
	},
	
	renderPlaceholder: function(current)	{
		this.subject.notifyEvent('RenderPlaceholder', {'node': current, 'callback': 'RenderingDone', 'id': this.name, 'state':'Edit'});
	},
	
	finishRendering: function()	{
		this.subject.notifyEvent('DisplayRemainingNodes', {'id': this.name});
		this._super();
		this.subject.notifyEvent("HideProfileChildren");
		this.subject.notifyEvent("ProfileInputBindEvent");
		var eventData = {};
		eventData.placeholder = this.requestForEffectiveResource('TabPlaceholder');
		eventData.tabs = Array();
		var tabCandidates = this.requestForMatchingEffectiveResource('ProfileMainContent', 'div.Heading_container[rootname]');
		$(tabCandidates).each(function (index, value)	{
			var tabCandidate = {};
			var heading = $(value).find('h2 span');
			tabCandidate.title = $(heading).html();
			//console.log(tabCandidate.title);
			if (tabCandidate.title != '')	{
				tabCandidate.id = $(value).attr('id');
				$(heading).parent().hide();
				eventData.tabs.push(tabCandidate);
			}
		});
		this.subject.notifyEvent("RenderProfileEditTab", eventData);
	},
	
	onMockupPlaceholderKeyup: function(eventData)	{
		var target = eventData.target;
		if ($(target).attr('modified') != 'true')
			return;
		if ($(target).val() != "" && $(target).attr('binded') == undefined)	{
			var ancestor = $(target).parents('div[mockup="true"]:first').parent();
			ancestor.siblings('.children_container').show();
			ancestor.parent().attr('id', $(ancestor).attr('id')+this.usedId);
			$(target).attr('binded', 'true');
			this.appendNewNode(target);
		}
	},
	
	appendNewNode: function(target)	{
		//find the nearest ancestor which contains a rootname attribute
		var ancestor = $(target).parent().parent().parent().parent().parent();
		var name = $(ancestor).attr('rootname');
		this.subject.notifyEvent('BuildMockupNode', {'id': this.name, 'nodeName': name, 'nodeBefore': ancestor});
		
		//call the finishRendering hook
		this.finishRendering();
	},
	
	onSaveProfile: function(eventData)	{
		var root = this.requestForEffectiveResource('ProfileMainContent');
		var dataToSent = {};
		dataToSent.profile_id = this.profile_id;
		dataToSent.data = Array();
		var obj = this;
		$(root).find('.profileData').each(function(index, value)	{
			if ($(value).attr('committed') == '1')	{
				return;
			}
			var ancestor = $(value).parents('.container:first');
			var prop_key = $(ancestor).attr('oid');
			if (prop_key == undefined || prop_key == '' || isNaN(prop_key))
				prop_key = $(ancestor).attr('rootname');
			if (prop_key == undefined)	{
				return;
			}
			var ancestorParent = $(ancestor).parents('[rootname]:first');
			var parent_key = $(ancestorParent).attr('oid');
			if (parent_key == undefined || parent_key == '' || isNaN(parent_key))
				parent_key = $(ancestorParent).attr('rootname');
			if (parent_key == undefined)	{
//				console.log('prop_key is undefined', ancestor);
				return;
			}
			
			var formatter = $(value).attr('formatter');
			var prop_val = "";
			$(value).attr('committed', '1');
			if (formatter == 'Normal')	{
				if ($(value).attr('modified') == 'true')
					prop_val = $(value).val();
//				else {
//					var mockup = $(value).parents('.normal-formatter').parent().attr('mockup');
//					if (mockup == 'true')	{
//						return;
//					}
//				}
			} else if (formatter == 'Date')	{
				if ($(value).attr('modified') == 'true')
					prop_val = $(value).val();
			} else if (formatter == 'Enum')	{
				prop_val = $(value).find('input:checked').attr('value');
				if (prop_val == undefined)	{
					prop_val = '';
				}
			} else if (formatter == 'List' || formatter == 'Email' )	{
				var listData = Array();
				$(value).find('label.lblToken').each(function(i, v)	{
//					prop_key = $(ancestor).attr('rootname');
					prop_key_oid = $(v).attr('oid');
					if (isNaN(prop_key_oid) || prop_key_oid == "")	{
						var val = $(v).html();
						var partial = obj.buildSavingData(prop_key, val, parent_key);
						dataToSent.data.push(partial);
//						console.log('push '+prop_key+':'+val);
					}
				});
				return;
			}
//			if (prop_val != "")	{
				var partial = obj.buildSavingData(prop_key, prop_val, parent_key);
				dataToSent.data.push(partial);
//			}
		});
		obj.requestForEffectiveResource('SaveSuccess').html('');
		obj.requestForEffectiveResource('SaveError').html('');
		dataToSent = $.toJSON(dataToSent);
//		console.log(dataToSent);
		this.onAjax('ajax', 'commit-profile', {'data': dataToSent}, 'POST', 
				{'onSuccess': function(ret)	{
//					console.log('success!');
					var subject = SingletonFactory.getInstance(Subject);
					subject.notifyEvent('NotifyGlobal', 'Bạn đã cập nhật thành công');
					subject.notifyEvent('RequestRoute', new Request('User'));
				},
				'onFailure': function(message)	{
					var successMsg = obj.getLocalizedText('SaveError');
					obj.requestForEffectiveResource('SaveError').html(successMsg);
				}});
	},
	
	buildSavingData: function(prop_key, prop_val, parent_key)	{
		var partial = {};
		partial.prop_key = prop_key;
		partial.prop_val = prop_val;
		partial.parent_key = parent_key;
		return partial;
	}
});

ProfileEditPlugin = Class.extend({
	init: function()	{
		this.name = "ProfileEditPlugin";
	},
	
	onHideProfileChildren: function(eventData)	{
		$('.children_container').each(function(index, value)	{
			var id = $(value).parent().attr('id');
			if (id.match("AddNew$"))	{
				//parent is mockup?
				$(value).hide();
			}
		});
	},
	
	onProfileInputBindEvent: function(eventData)	{
		$('div[mockup="true"] input.profileData').bind('blur', function(event)	{
			generateEvent('MockupInputBlur', event);
			generateEvent('MockupPlaceholderKeyup', event);
		});
		
		$('.normal-formatter input.profileData,.normal-large-formatter textarea.profileData').bind('change', function(event)	{
			generateEvent('NormalInputChange', event);
		});
		
		$('div[mockup="true"] input.profileData').bind('focus', function(event)	{
			generateEvent('MockupInputFocus', event);
		});
	},
	
	onNormalInputChange: function(eventData)	{
		var target = eventData.target;
		$(target).attr('modified', 'true');
	},
	
	onMockupInputBlur: function(eventData)	{
		var target = eventData.target;
		if ($(target).val() == '')
			$(target).attr('modified', '');
		if ($(target).attr('modified') == 'true')
			return;
		$(target).val($(target).attr('oldVal'));
		$(target).addClass('formatterInputInsert');
	},
	
	onMockupInputFocus: function(eventData)	{
		var target = eventData.target;
		if ($(target).attr('modified') == 'true')	{
			return;
		}
		if ($(target).val() != '')
			$(target).attr('oldval', $(target).val());
		$(target).val('');
		$(target).removeClass('formatterInputInsert');
	}
}).implement(PluginInterface);
GmailInvitation = Class.extend({
	
	init: function()	{
		var obj = this;
		this.scope = "https://www.google.com/m8/feeds";
		this.contactsService = new google.gdata.contacts.ContactsService('BKProfile-GmailContactFeed-1.0');
	},
	
	setCallback: function(callback)	{
		this.callback = callback;
	},
	
	checkLogin: function()	{
		return (google.accounts.user.checkLogin(this.scope));
	},
	
	logMeOut: function()	{
		google.accounts.user.logout(function() {}, this.scope);
	},
	
	authenticate: function()	{
		if (google.accounts.user.checkLogin(this.scope))	{
			this.onAuthReady();
			return;
		}
		var w = 600;
		var h = 450;
		var left = (screen.width/2)-(w/2);
		var top = (screen.height/2)-(h/2);
		var popup = window.open('invite.html', 'authWindow', "status = 0, height = "+h+", width = "+h+", resizable = 0, left = "+left+", top = "+top);
	},
	
	feedContact: function(maximum)	{
		var contactsFeedUri = 'https://www.google.com/m8/feeds/contacts/default/full';
		var query = new google.gdata.contacts.ContactQuery(contactsFeedUri);
		  
		// Set the maximum of the result set to be 10
		query.setMaxResults(maximum);
		
		var obj = this;
		this.contactsService.getContactFeed(query, function(result) {obj.callback(result)}, function() {});
	}
});

InvitationPortlet = Class.extend({
	init: function()	{
		this.name = "InvitationPortlet";
	},
	
	onBegin: function()	{
		this.registerObserver();
		this.currentMaxContacts = 50;
		this.invitationImpl = new GmailInvitation();
		this.invitationImpl.setCallback(function(result) {
			var subject = SingletonFactory.getInstance(Subject);
			subject.notifyEvent('FeedContacts', result);
		});
	},
	
	onSendInviteButtonClick: function(eventData)	{
		var email = eventData.email;
		var origin = eventData.origin.target;
		var plhd = $(origin).parent();
		plhd.html('<img class="invite-ajax-loader" src="static/images/ajax-loader-1.gif">');
		this.onAjax('invitation', 'send-invitation', {'email': email}, 'POST', {
			'onSuccess': function()	{
				$(plhd).html('<strong class="InvitationSent">Đã gửi lời mời</strong>')
			},
			
			'onFailure': function()	{
				$(plhd).html('<div class="errorMsg">Gửi thất bại!</div>');
			}
		});
	},
	
	onFeedContacts: function(result)	{
		var entries = result.feed.entry;
		var contacts = Array();
		var emails = Array();
		for (var i = 0; i < entries.length; i++) {
			var contact = {};
			var contactEntry = entries[i];
			var photoLink = contactEntry.getContactPhotoLink();
			if (photoLink != undefined)	{
				photo = photoLink.getHref();
			}
			else
				photo = "styles/images/unknown.png";
			if (contactEntry.getTitle() && contactEntry.getTitle().getText())	{
				contact.name = contactEntry.getTitle().getText();
			} else {
				contact.name = "";
			}
			contact.photo = photo;
			contact.emails = Array();
		    var emailAddresses = contactEntry.getEmailAddresses();
		    var emailAddress = emailAddresses[0].address;
		    if (emailAddress == this.currentEmail)	{
		    	continue;
		    }
		    emails.push(emailAddress);
		    contact.email = emailAddress;
		    contacts.push(contact);
		}
		
		var existing = Array();
		var pendingArr = Array();
		var obj = this;
		this.onAjax('invitation', 'get-invite-users-from-emails', {'emails': emails}, 'GET', {
			'onSuccess': function(ret)	{
				var exist = ret.existing;
				var pending = ret.pending;
				
				for(var i=0;i<exist.length;i++)	{
					var email = exist[i].email;
					//remove contacts which exists in our system
					for(var j in contacts)	{
						var contact = contacts[j];
						if (contact.email == email)	{
							contacts.splice(j, 1);
							break;
						}
					}
					existing.push(exist[i]);
				}
				
				for(var i=0;i<pending.length;i++)	{
					var email = pending[i].email;
					//remove contacts which exists in our system
					for(var j in contacts)	{
						var contact = contacts[j];
						if (contact.email == email)	{
							contacts.splice(j, 1);
							break;
						}
					}
					pendingArr.push(pending[i]);
				}
				
				obj.currentContacts = contacts;
				obj.requestForEffectiveResource('PendingContactsFeed').html(obj.renderView('PendingContacts', {'contacts': pendingArr}));
				obj.requestForEffectiveResource('ExistingContactsFeed').html(obj.renderView('ExistingContacts', {'contacts': existing}));
				obj.requestForEffectiveResource('ContactsFeed').html(obj.renderView('Contacts', {'contacts': contacts}));
				obj.requestForEffectiveResource('MoreFeed').show();
				var target = obj.requestForEffectiveResource('EmailFilter');
				var subject = SingletonFactory.getInstance(Subject);
				subject.notifyEvent('AttachFocusDetection', {'target': target, 'defaultValue': 'Nhập tên/email để tìm kiếm'});
				
				//filtering function
				$(target).keyup(function()	{
					var val = $(target).val();
					for(var i=0;i<obj.currentContacts.length;i++)	{
						if (obj.currentContacts[i].name.indexOf(val) == -1 && obj.currentContacts[i].email.indexOf(val) == -1)	{
							$('div[contactID="'+i+'"]').hide();
						} else {
							$('div[contactID="'+i+'"]').show();
						}
					}
				});
			}
		});
	},
	
	feed: function()	{
		this.invitationImpl.feedContact(this.currentMaxContacts);
		this.currentMaxContacts += 20;
	},
	
	onFeedMoreContacts: function()	{
		this.feed();
	},
	
	onInviteButtonClicked: function()	{
		this.feed();
	},
	
	onAuthSubAuthenticateButtonClick: function()	{
		this.invitationImpl.authenticate();
	},
	
	run: function()	{
		this.model = {};
		this.getPortletPlaceholder().paintCanvas(this.render());
		if (!this.invitationImpl.checkLogin())	{
			this.startInterval(500, function() {
				if (this.invitationImpl.checkLogin())	{
					this.requestForEffectiveResource('AuthenButton').html('Cho phép thành công');
					this.requestForEffectiveResource('AuthenButton').attr('disabled', 'disabled');
					this.requestForEffectiveResource('FeedMe').removeAttr('disabled');
					this.stopInterval();
				}
			});
			this.requestForEffectiveResource('FeedMe').attr('disabled', 'disabled');
			this.requestForEffectiveResource('AuthStep').html(this.renderView('Authenticate', {}));
		}
		var loggedIn = SingletonFactory.getInstance(Application).getSystemProperties().get('user.login');
		if (loggedIn == 1)	{
			var obj = this;
			this.onAjax('user-ajax', 'get-user-email', {}, 'GET', {
				'onSuccess': function(ret)	{
					obj.currentEmail = ret;
				}
			});
		}
	},
	
	onEnd: function()	{
		this.unregisterObserver();
		this.stopInterval();
	}
}).implement(PortletInterface).implement(RenderInterface).implement(AjaxInterface).implement(ObserverInterface).implement(IntervalTimerInterface);

/**
 * 
 */

FooterPortlet = Class.extend({
	init:function() {
		this.name = "FooterPortlet";
		this.ids = new Array("AboutUs","Tutorial","Faq","Tou","Piracy","Architecture");
		this.activeId = undefined; 
	},
	
	requestForResource: function(resourceName){
		var app = SingletonFactory.getInstance(Application);
		var rm = app.getResourceManager();
		return rm.requestForResource(this.name,resourceName);
	},
	
	onReloadPage: function()	{
		var page = this.getRequest().getParam('page');
		if (page != 'Documentation')	{
			for( var i=0; i < this.ids.length; i++ ){
				if(this.requestForEffectiveResource(this.ids[i]) != undefined ){
					if(this.requestForEffectiveResource(this.ids[i]).hasClass("footeritem_active")){
						this.requestForEffectiveResource(this.ids[i]).removeClass("footeritem_active");
					}
				}
			}
		}
	},
	
	setActive: function(id){
		this.activeId = id;
		for( var i=0; i < this.ids.length; i++ ){
			if(this.requestForEffectiveResource(this.ids[i]) != undefined ){
				if(this.requestForEffectiveResource(this.ids[i]).hasClass("footeritem_active")){
					this.requestForEffectiveResource(this.ids[i]).removeClass("footeritem_active");
				}
			}
		}
		if(this.requestForEffectiveResource(id) != undefined ){
			this.requestForEffectiveResource(id).addClass("footeritem_active");
		}
	},

	run: function() {
		this.getPortletPlaceholder().drawToCanvas(this.render());
		if(this.activeId != undefined){
			this.setActive(this.activeId);
		}
	}
}).implement(RenderInterface).implement(PortletInterface);
/**
 * 
 */

HeaderPortlet = Class.extend({
	init:function() {
		this.name = "HeaderPortlet";
	},
	
	requestForResource: function(resourceName){
		var app = SingletonFactory.getInstance(Application);
		var rm = app.getResourceManager();
		return rm.requestForResource(this.name,resourceName);
	},
	
	run: function() {
		this.getPortletPlaceholder().drawToCanvas(this.render());
		$("#"+this.placeholder.canvas.id).css("overflow","visible");
		$("#"+this.placeholder.canvas.id).css("float","left");
		$("#"+this.placeholder.canvas.id).css("vertical-allign","bottom");
	}
}).implement(RenderInterface).implement(PortletInterface);
/**
 * 
 */

ErrorPortlet = Class.extend(
		{
			init : function() {
				this.name = "ErrorPortlet";
				this.model = {};
				this.heading = "";
				this.errorCode = "";
				this.data = {};
			},
			
			onBegin: function()	{
				this.registerObserver();
				this.getHandledErrorCode();
				this.prepareData();
				this.prepareTemplate();
			},
			
			getHandledErrorCode: function(){
				var data = tmpl("ErrorPortlet-HandledErrorCode",{});
				return eval(data);
			},
			
			checkErrorCode: function(errorCode){
				if(errorCode == undefined || errorCode == null){
					return true;
				}
				var data = this.getHandledErrorCode();
				for(var key in data){
					if(data[key] == errorCode){
						return true;
					}
				}
				return false;
			},
			
			prepareData: function(){
				var request = SingletonFactory.getInstance(Page).getRequest();
				var params = request.getParams();
				this.errorCode = params["code"] || 404;
				this.heading = params["msg"] || this.getMsgHeading("");;
				this.data = params['content'] || this.getMsgContent("");
				if(this.checkErrorCode(this.errorCode)){
					this.heading = this.getMsgHeading(this.errorCode);
					this.data = this.getMsgContent(this.errorCode);
				}
			},
			
			prepareTemplate: function(){
				this.model.errorHeader = this.heading;
				this.model.errorContent = this.data;
			},
			
			getMsgHeading: function(errorCode){
				var errorCodeID = "ErrorCode" + errorCode;
				return this.getPrefetchData(errorCodeID, "_Heading");
			},
			
			getMsgContent: function(errorCode){
				var errorCodeID = "ErrorCode" + errorCode;
				return this.getPrefetchData(errorCodeID, "_Content");
			},
			
			getPrefetchData: function(id,type){
				try{
					return tmpl(this.name + "-" + id + type,{});
				}
				catch(ex){
					return tmpl(this.name + "-" + "ErrorCode" + type,{});
				}
			},

			run : function() {
				this.getPortletPlaceholder().drawToCanvas(this.render());
			},
			
			onEnd: function()	{
				this.unregisterObserver();
			}
		}).implement(RenderInterface).implement(PortletInterface).implement(ObserverInterface);


/**
 * 
 */

NavigationPortlet = Class.extend({
	init:function() {
		this.name = "NavigationPortlet";
		this.viewId = "NavigationPortlet-NavigationPortlet";
		this.pageName = "";
		this.pageHeader = "";
		this.pageClass = "";
	},

	buildTemplate: function(){
		var data = this.getPageData();
		var pages = data.pages;
		var dataChildren = Array();
		for(var key in pages){
			var obj = {};
			obj.pageHeader = pages[key].pageHeader;
			obj.pageClass = pages[key].pageClass;
			obj.pageName = pages[key].pageContent;
			dataChildren.push(tmpl(this.name + "-Item", obj));
		}
		
		var objParam = {};
		objParam.children = dataChildren;
		return tmpl(this.name + "-List",objParam);
	},
	
	getPageData: function(){
		var pageName = SingletonFactory.getInstance(Page).getRequest().getName();
		var data = null;
		if(this.requestForResource("Config" + pageName) == undefined){
			data = tmpl(this.name + "-Config",{}); 
		} else {
			data = tmpl(this.name + "-Config" + pageName,{});
		}
		return eval('('+data+')');
	},
	
	render: function(){
		//console.log($(this.buildTemplate()));
		return $(this.buildTemplate()).children();
	},
	
	run: function() {
		this.getPortletPlaceholder().drawToCanvas(this.render());
		$("#"+this.placeholder.canvas.id).css("float","left");
		$("#"+this.placeholder.canvas.id).css("margin-left","-150px");
		$("#"+this.placeholder.canvas.id).css("margin-top","50px");
		$("#"+this.placeholder.canvas.id).css("background-color","#f5f3f4");
		$("#"+this.placeholder.canvas.id).css("-moz-border-radius","10px 10px 10px 10px");
		$("#"+this.placeholder.canvas.id).css("-webkit-border-radius","10px 10px 10px 10px");
		$("#"+this.placeholder.canvas.id).css("border-radius","10px 10px 10px 10px");
		$("#"+this.placeholder.canvas.id).css("min-width","150px");
	}
}).implement(RenderInterface).implement(PortletInterface);
/**
 * 
 */


// Profile only!!!
SearchResultPortlet = Class.extend(
		{
			init : function() {
				this.name = "SearchResultPortlet";
				this.model = {};
				this.pageType = "";//Profile; Knowledge; 
				this.query = "";
				this.dataResJSON = null;
				this.highlightResJSON = null;
				// để biết xem thằng nào trước thằng nào sau.
				this.itemOrder = null;
				this.numDocs = null;
				this.start = null;
				this.rows = null;
				this.ajaxProfileArr = Array();
				this.root = SingletonFactory.getInstance(Application).getSystemProperties().get("host.root");
			},
			
			onBegin: function()	{
				this.registerObserver();
				this.prepareData();
			},
			
			// done
			prepareData: function(){
				var request = SingletonFactory.getInstance(Page).getRequest();
				var params = request.getParams();
				this.query = params['query'];
				this.pageType = params['type'];
				this.searchPage = params['search-page'] || 1;
				this.rows = params['rows'] || 10;
				this.configData = this.getConfigData();
				this.getDataFromServer();
				this.getAllKeywords();
			},
			
			getDataFromServer: function(){
				var currentPorlet = {};
				var root = SingletonFactory.getInstance(Application).getSystemProperties().get("host.root");
				var urlStr = root + "ajax/get-search-result/query/" + this.query + "/searchPage/" + this.searchPage + "/rows/" + this.rows;
				$.ajax({url:urlStr, async: false, success: function(ret){
						ret = $.parseJSON(ret);
						if(ret.result != undefined){
							ret = $.parseJSON(ret.result);
							currentPorlet.numDocs = ret.response.numFound;
							currentPorlet.dataResJSON = ret.response.docs;
							currentPorlet.highlightResJSON = ret.highlighting;
						} else {
							//console.log("Lỗi xảy ra");
						}
					}
				});
				
				this.numDocs = currentPorlet.numDocs;
				this.dataResJSON = currentPorlet.dataResJSON;
				this.highlightResJSON = currentPorlet.highlightResJSON;
			},
			
			// done
			// return json object
			getHighlight: function(profileID, fieldName){
				if(this.highlightResJSON[profileID] == undefined || this.highlightResJSON[profileID][fieldName] == undefined){
					return null;
				}
				return this.highlightResJSON[profileID][fieldName];
			},
			
			// done
			getConfigData: function(){
				try{
					var data = eval("(" + tmpl(this.name + "-ItemConfig" + this.pageType,{}) + ")");
					// iterate through json sent from server and build template arcording to view type
					var hashConfig = Array(); 
					// item order
					var orderItemHelper = $("<div></div>");
					for(var key in data){
						for(var k in data[key]){
							hashConfig[data[key][k].type] = key;
						}
						$(orderItemHelper).append($("<div class='"+key+"'></div>"));
					}
					this.itemOrder = $(orderItemHelper);
					return hashConfig;
				}
				catch(ex){
					//console.log("Cannot find ItemConfig" + this.pageType + " -- " + ex);
				}
				return null;
			},
			
			getAllKeywords: function(){
				var sysProp = SingletonFactory.getInstance(Application).getSystemProperties();
				if(sysProp.get("host.keywordsMap") != undefined){
					return;
				}
				
				//ajax
				$.ajax( {url:this.root + 'ajax/get-all-keywords', async:false, success:	function(ret)	{
							ret = $.parseJSON(ret);
							ret = ret.result;
							var result = Array();
							for(var key in ret){
								result[ret[key].keyword] = ret[key].content; 
							}
							sysProp.set("host.keywordsMap",result);
						}
				});
			},
			
			buildSearchItems: function(){
				var keywordsMap = SingletonFactory.getInstance(Application).getSystemProperties().get("host.keywordsMap");
				var keywordCheck = Array();
				var finalResult = Array();
				// build template for each type => single []; list []; highlightResJSON []
				var profileID = -1;
				var originalItemOrder = null;
				var originalPlhld = $(this.getSearchItemPlhld());
				var name = "";
				var linkImg = null;
				
				for(var index in this.dataResJSON) {
					//each profile goes here 
					var searchItemPlhld = $(originalPlhld).clone();
					profileID = this.dataResJSON[index].profile_id;
					this.ajaxProfileArr.push(profileID);
					originalItemOrder = this.itemOrder.clone();
					
					name = this.dataResJSON[index].name_indexed || this.dataResJSON[index].name_unindexed;
					linkImg = null;
					// preview
					for(var field in this.dataResJSON[index]){
						if(field == "profile_id"){
							continue;
						}
						
						var keyword = this.normalizeKeyword(field);
						var type = this.configData[keyword];
						
						if(keyword == "avatar"){
							linkImg = this.dataResJSON[index][field];
							continue;
						}
						 
						if(keyword == "name" ){
							var tmpName = this.getHighlight(profileID, field); 
							if(tmpName != undefined){
								name = tmpName;
							}
						}
						
						if(type != undefined){
							//check highlightResJSON for this keyword
							var hl = this.getHighlight(profileID, field); 
							if(hl != undefined){
								keywordCheck[profileID + "_" + keyword] = true;
								this.dataResJSON[index][field] = hl;
							}

							// data param to templating
							var objParams = {};
							objParams.header = keywordsMap[keyword];
							
							// if type== List => need children
							if(type == "List"){
								// find children
								var objParamsArr = Array();
								for(var k in this.dataResJSON[index][field]){
									var objParam = {};
									objParam.content = this.dataResJSON[index][field][k];
									objParamsArr.push(this.buildPartialTemplate(objParam, "ListItem"));
								}
								objParams.content = objParamsArr;
							} 
							// else just content
							else {
								objParams.content = this.dataResJSON[index][field];
							}
							
							originalItemOrder.children("." + type).append($(this.buildPartialTemplate(objParams, type)));
						}
					}
					
					$(searchItemPlhld).children(".search_result_main").children(".search_result_preview").append(originalItemOrder.children().children());
					
					// highlight
					for(var field in this.highlightResJSON[profileID]){
						var keyword = this.normalizeKeyword(field);
						if(keywordCheck[profileID + "_" + keyword] == undefined){
							var objParam = {};
							objParam.header = keywordsMap[keyword];
							objParam.content = this.highlightResJSON[profileID][field];
							$(searchItemPlhld).children(".search_result_highlight").append(this.buildPartialTemplate(objParam, "Highlight"));
						}
					}
					
					var linkProfile = "#page/ProfilePage/id/" + profileID; 
					linkImg = linkImg == null? "styles/images/unknown.png" : linkImg;
					
					var objParam = {};
					objParam.name = name;
					objParam.link = linkProfile;
					objParam.profileid = profileID;
					searchItemPlhld.children(".search_result_brief").append(this.buildPartialTemplate(objParam, "BriefInfo"));
					
					objParam = {};
					objParam.linkProfile = linkProfile;
					objParam.linkImg = linkImg;
					searchItemPlhld.children(".search_result_main").children(".search_result_pic").append($(tmpl("SearchResultPortlet-LinkImg",objParam)));
					
					this.setHighlightKeywords(searchItemPlhld);
					finalResult.push($("<div></div>").append(searchItemPlhld));
				}
				return finalResult;
			},
			
			buildSearchNavigation: function(){
				return this.fetchPageLink();
			},
			
			fetchPageLink: function(){
				var result = $("<div></div>");
				var numPages = parseInt(this.numDocs / this.rows);
				if(numPages == 0){
					numPages = 1;
				}
				var curPage = parseInt(this.searchPage); 
				var pageLinks = Array();
				if (curPage > numPages){
					curPage = numPages;
				}
				if (curPage <= 0){
					curPage = 1;
				}
				
				for(var x = 1; x <= numPages; x ++) {
					if (x == curPage) {
						var objParam = {};
						objParam.content = x;
						pageLinks[x-1] = tmpl("CommonPortlet-NavCurrent",objParam);
					} else {
						var objParam = {};
						objParam.query = this.query;
						objParam.pageType = this.pageType;
						objParam.searchPage = x;
						objParam.content = x;
						objParam.rows = this.rows;
						objParam.searchController = "SearchResult";
						pageLinks[x-1] = tmpl("CommonPortlet-NavOther",objParam);
					}
				}
				
				if (curPage > 1 && curPage <= pageLinks.length){
					var objParam = {};
					objParam.query = this.query;
					objParam.pageType = this.pageType;
					objParam.searchPage = curPage-1;
					objParam.content = "&#171 Trước&nbsp;";
					objParam.rows = this.rows;
					objParam.searchController = "SearchResult";
					result.append(tmpl("CommonPortlet-NavOther",objParam));
				}
				
				
				for (var key= curPage-11; key <= curPage+9; key++ ) {
					if (key<0) continue;
					if (key>= pageLinks.length) continue;
					if (key == curPage)
						result.append(pageLinks[key]);
					else
						result.append(pageLinks[key]);
				}		
				
				if(curPage < pageLinks.length){
					var objParam = {};
					objParam.query = this.query;
					objParam.pageType = this.pageType;
					objParam.searchPage = curPage+1;
					objParam.content = "&nbsp;Sau&nbsp;&#187";
					objParam.rows = this.rows;
					objParam.searchController = "SearchResult";
					result.append(tmpl("CommonPortlet-NavOther",objParam));
				}
				return result;
			},
			
			setHighlightKeywords: function(element){
				element.find("em").addClass("bkp_search_highlight");
			},
			
			getSourcePercentage: function(profileid){
				//ajax
				$.get(
						this.root + 'ajax/get-source-percentage',
						{'id':profileid},
						function(ret)	{
							ret = $.parseJSON(ret);
							if (ret == null)	{
								$('.errorMsg-' + profileid).html('Thông báo: Không lấy được thông tin về nguồn ');
							} else if (ret.result=='error')	{
								$('.errorMsg-' + profileid).html('Thông báo: '+ret.message);
							} else {
								$('.errorMsg-' + profileid).html('');
								$("#vertgraph-"+profileid).empty();
								var leftMargin = 0;
								for(key in ret.result){
									leftMargin += 50;
									var value = ret.result[key].percent;
									var color = ret.result[key].color;
									var objParam = {};
									objParam.name = key;
									objParam.height = Math.round(50 * value);
									objParam.value = Math.round(100 * value*10)/10 + "%";
									objParam.color = color;
									objParam.left = leftMargin;
									var microTemplateBar = tmpl("SearchResultPortlet-sourcePerPlhld",objParam);
									$("#vertgraph-"+profileid).append(microTemplateBar);
								}
							}
							return false;
						}
					);
			},
			
			// done
			normalizeKeyword:function(keyword){
				var ret = keyword.replace("_indexed","");
				ret = ret.replace("_unindexed","");
				return ret;
			},

			// done
			fetchToMainView: function(){
				var id = "SearchResultPortlet-ViewPrefetch";
				var obj = {};
				obj.children = this.buildSearchItems();
				obj.navigator = this.buildSearchNavigation();
				return tmpl(id, obj);
			},
			
			// done
			getSearchItemPlhld: function(){
				var id = this.name + "-Item"+ this.pageType + "-View";
				return tmpl(id, {});
			},
			
			// done
			buildPartialTemplate: function(data, type){
				//single; list; highlightResJSON
				var id = this.name + "-Item" + this.pageType + "-" + type;
				return tmpl(id,data);
			},
			
			// done
			render: function(){
				return this.fetchToMainView();
			},
			
			// done
			run : function() {
				this.getPortletPlaceholder().drawToCanvas(this.render());
				this.loadAjax();
			},
			
			loadAjax: function(){
				// load all ajax here;
				// dump all profile into array
				//console.log("ajax");
				for(var key in this.ajaxProfileArr){
					this.getSourcePercentage(this.ajaxProfileArr[key]);
				}
			},
			
			onEnd: function()	{
				this.unregisterObserver();
			}
		}).implement(RenderInterface).implement(PortletInterface).implement(ObserverInterface);


/**
 * 
 */


// Profile only!!!
SearchResultDynamicPortlet = Class.extend(
		{
			init : function() {
				this.name = "SearchResultDynamicPortlet";
				this.model = {};
				this.pageType = "";//Profile; Knowledge; 
				this.query = "";
				this.configData = null;
				this.dataResJSON = null;
				this.highlightResJSON = null;
				this.numDocs = null;
				this.start = null;
				this.rows = null;
				this.root = SingletonFactory.getInstance(Application).getSystemProperties().get("host.root");
				this.searchCore = "";
			},
			
			onBegin: function()	{
				this.registerObserver();
				this.prepareData();
			},
			
			// done
			prepareData: function(){
				var request = SingletonFactory.getInstance(Page).getRequest();
				var params = request.getParams();
				this.query = params['query'] || "*:*";
				this.core = params['type'] || "notification-filter";
				this.expertises = params['expertises'];
				this.profileExcluded = params['profileExcluded'];
				
				// fixed
				switch(this.core){
					case "person-search" :
					case "person-best" :
					case "person-hardcore" :
					case "person-similar" :
					case "person-recommendation":
						this.pageType = "Person";
						break;
					case "question-search" :
					case "question-latest" :
					case "question-best" :
					case "catchword-filter" :
						this.pageType = "Knowledge";
						break;
					case "notification-filter":
						this.pageType = "Notification";
						break;
					default:
						this.pageType = "Knowledge";
						break;
				}
//				if(this.core == "person-search"){
//					this.pageType = "Person";
//				} else if (this.core == "notification-filter") {
//					this.pageType = "Notification";
//				} else {
//					this.pageType = "Knowledge";
//				}
				
				this.searchPage = params['search-page'] || 1;
				this.rows = params['rows'] || 10;
				this.configData = this.getConfigData();
				
					
				//console.log("Pagetype:" + params['type']);
			},
			
			processQuery: function(query){
				// split by space
				if(query.indexOf("#") != -1){
					query = query.replace(/[#]/g,escape("#"));
				} 
				
				if(query.indexOf("%") != -1){
					query = query.replace(/[%]/g,escape("%"));
				}
				
				if(this.core == "catchword-filter"){
					query = '%22' + query + '%22';
				}
				
				return query;
			},
			
			// good
			getDataFromServer: function(){
				var currentPorlet = {};
				var obj = this;
				var root = SingletonFactory.getInstance(Application).getSystemProperties().get("host.root");
				var urlStr = root + "ajax/get-search-dynamic/search-page/" + this.searchPage + "/rows/" + this.rows + "/type/" + this.core.toLowerCase();
				// for hardcore person search
				if(this.expertises != null && this.expertises != ""){
					urlStr += "/expertises/" + this.expertises;
				}
				// for hardcore similar search
				if(this.profileExcluded != null && this.profileExcluded != ""){
					urlStr += "/profileExcluded/" + this.profileExcluded;
				}
				urlStr += "/query/" + this.processQuery(this.query);
				$.ajax({url:urlStr, success: function(ret){
						try{
							ret = $.parseJSON(ret);
							if(ret.result != undefined){
								ret = $.parseJSON(ret.result);
								currentPorlet.numDocs = ret.response.numFound;
								currentPorlet.dataResJSON = ret.response.docs;
								currentPorlet.highlightResJSON = ret.highlighting;
							} else {
								currentPorlet.numDocs = 0;
								currentPorlet.dataResJSON = {};
								currentPorlet.highlightResJSON = {};
							}
						} catch(e) {
							currentPorlet.numDocs = 0;
							currentPorlet.dataResJSON = {};
							currentPorlet.highlightResJSON = {};
						}
						obj.numDocs = currentPorlet.numDocs;
						obj.dataResJSON = currentPorlet.dataResJSON;
						obj.highlightResJSON = currentPorlet.highlightResJSON;
						obj.buildSearchItems();
						obj.getPortletPlaceholder().paintCanvas(obj.render());
						var sbj = SingletonFactory.getInstance(Subject);
						sbj.notifyEvent("CheckMoreLessContent");
						obj.buildSearchNavigation();
						obj.buildSearchHeader();
					}
				});
			},
			
			// done
			// return json object
			getHighlight: function(profileID, fieldName){
				if(this.highlightResJSON[profileID] == undefined || this.highlightResJSON[profileID][fieldName] == undefined){
					return null;
				}
				return this.highlightResJSON[profileID][fieldName];
			},
			
			// done
			getConfigData: function(){
				try{
					var id = this.name + "-ItemConfig" + this.pageType;
					//console.log("id is: " + id);
					var data = eval("(" + tmpl(id,{}) + ")");
					// iterate through json sent from server and build template arcording to view type
					var hashConfig = Array();
					// item order
					for(var key in data){
						hashConfig[key] = data[key];
					}
					return hashConfig;
				}
				catch(ex){
					//console.log("Cannot find ItemConfig" + this.pageType + " -- " + ex);
				}
				return null;
			},
			
			buildSearchItems: function(){
				var searchItems = Array();
				if((this.numDocs == 0 || this.dataResJSON.length == 0)){
					if(this.configData['notShowNoResult']== undefined || this.configData['notShowNoResult']== false) {
						this.numDocs = 0;
						searchItems.push(tmpl("CommonPortlet-NoResult",{}));
						this.model.children = searchItems;
						return;
					}
				}
				for(var key in this.dataResJSON){
					var curRes = this.dataResJSON[key];
					// 1 search result
					var objParam = {};
					var uiFields = this.configData['uifields'];
					for(var keyConfig in uiFields){
						for(var field in uiFields[keyConfig]){
							var templateName = uiFields[keyConfig][field];
							// get loop
							objParam[field] = this.buildSearchItemTemplate(templateName, curRes);
						}
					}
					var searchItem = $(this.buildSearchItem(objParam));
					var sbj = SingletonFactory.getInstance(Subject);
					sbj.notifyEvent("RequestCheckAnswerContent",searchItem);
					searchItems.push(searchItem);
				}
				this.model.children = searchItems;
			},
			
			// done
			buildSearchItem: function(objParam){
				var id = this.name + "-Item"+ this.pageType + "-Main";
				return tmpl(id, objParam);
			},
			
			// done
			buildSearchItemTemplate: function(templateName, curRes){
				var objParam = {};
				var templateKey = this.name + "-Item" + this.pageType + "-" + templateName;
				var fieldMaps = this.configData[templateName].data;
				
				for(var fieldMap in fieldMaps){
					// placeholderName => fieldMap
					var currentFieldMap = fieldMaps[fieldMap]; 
					
					var fieldRes = currentFieldMap.field;
					var type = currentFieldMap.type;
					var templateName = currentFieldMap.template;
					
					var curObjVal = curRes[fieldRes];
					var ret = null;
					
					switch(type){
						case "multiple":
							// Có nhiệm vụ lấy thông tin kiểu link, có cả id, cả content.
							// Cần truyền vào curObjVal để nó biết là cần duyệt ở cột nào.
							// array của dataJSON
							ret = this.buildSearchItemMultipleHelper(templateName, curRes, curObjVal);
							break;
						case "advanced":
							// có chữ cái cuối cùng == _1; _3...
							ret = this.buildSearchItemAdvancedHelper(templateName, curRes, fieldRes);
							break;
						case "single":
						default:
							// Chỉ lấy thông tin dạng đơn 
							// text value
							ret = curObjVal;
							break;
					}
					objParam[fieldMap] = ret;
				}
				return tmpl(templateKey, objParam);
			},
			
			// Lấy cái con cấp 2; Chắc chắn chỉ có 2 cấp
			// Cái này chuyên để lấy những thứ như id đi kèm vs cái j đó
			// để lấy link chẳng hạn.
			buildSearchItemMultipleHelper: function(templateName, curRes, curObjVal){
				var ret = $("<div></div>");
				var id = this.name + "-Item" + this.pageType + "-" + templateName;
				for (var pos in curObjVal){
					var fieldMaps = this.configData[templateName].data;
					var objParam = {};
					for(var fieldMap in fieldMaps){
						// placeholderName => fieldMap
						var fieldRes = fieldMaps[fieldMap].field;
						objParam[fieldMap] = curRes[fieldRes][pos];
					}
					ret.append(tmpl(id, objParam));
				}
				return ret.html();
			},
			
			buildSearchItemAdvancedHelper: function(templateName, curRes, fieldRes){
				var ret = $("<div></div>");
				var id = this.name + "-Item" + this.pageType + "-" + templateName;
				// đầu tiên phải chỉ định trường id là trường nào.
				var idCol = fieldRes + "_id"; 
				// lấy id của trường đó. => quy định hẳn là tên trường + _id
				var curObjVal = curRes[fieldRes];
				for (var pos in curObjVal){
					var curID = curRes[idCol][pos];
					var fieldMaps = this.configData[templateName].data;
					var objParam = {};
					for(var fieldMap in fieldMaps){
						var fieldCheck = fieldMaps[fieldMap].field;
						//console.log(curID);
						var curField = (fieldCheck == idCol || fieldCheck == fieldRes) ?  fieldCheck : fieldCheck + "_" + curID;
						objParam[fieldMap] = curRes[curField][pos] == null ? "" : curRes[curField][pos];
					}
					ret.append(tmpl(id, objParam));
				}
				return ret.html();
			},
			
			buildSearchNavigation: function(){
				if(this.configData["showNavigator"] == undefined || this.configData["showNavigator"]){
					var objParam = {};
					objParam.numDocs = this.numDocs;
					objParam.rows = this.rows;
					objParam.searchPage = this.searchPage;
					objParam.dataLength = this.dataResJSON.length;
					objParam.query = this.query;
					objParam.core = this.core;
					objParam.searchController = "Search";
					var sbj = SingletonFactory.getInstance(Subject);
					sbj.notifyEvent("FetchNavigationLink", objParam);
				}
			},
			
			buildSearchHeader: function(){
				if(this.configData["showSearchResult"] == undefined || this.configData["showSearchResult"]){
					var objParam = {};
					objParam.numDocs = this.numDocs;
					var sbj = SingletonFactory.getInstance(Subject);
					sbj.notifyEvent("FetchSearchResultNumber", objParam);
				}
			},
			
			setHighlightKeywords: function(element){
				element.find("em").addClass("bkp_search_highlight");
			},
			
			// done
			normalizeKeyword:function(keyword){
				var ret = keyword.replace("_indexed","");
				ret = ret.replace("_unindexed","");
				return ret;
			},
			
			// done
			run : function() {
				this.getDataFromServer();
				//console.log("PageType:" + this.pageType);
			},
			
			onReloadPage: function(){
				this.onBegin();
				this.run();
			},
			
			onGetMoreResultRows: function()	{
				if (this.rows == undefined)
					this.rows = this.getRequest().getParam('rows') || 10;
				this.rows += 10;
				this.run();
			},
			
			onEnd: function()	{
				this.unregisterObserver();
			}
		}).implement(RenderInterface).implement(PortletInterface).implement(ObserverInterface);


/**
 * 
 */

AnswerPortlet = Class.extend({
	init : function() {
		this.name = "AnswerPortlet";
		this.model = {};
		this.question = null;
		this.topics = null;
		this.topicsQuestion = null;
		this.mce = $("");
		this.answers = null;
		this.questionID = null;
		this.needMCE = true;
		this.answerNum = 0;
		this.root = SingletonFactory.getInstance(Application).getSystemProperties().get("host.root");
		this.uid = SingletonFactory.getInstance(Application).getSystemProperties().get("user.id");
		this.quid = "";
	},

	onBegin : function() {
		this.registerObserver();
		this.getQuestionID();
		this.model.qid = this.questionID;
		this.model.qvoteup = "...";
		this.model.qvotedown = "...";
		this.model.avaiTopics = {};
		this.model.topics = {};
		this.model.mce = {};
		this.model.children = {};
	},
	
	getQuestionID: function(){
		var request = SingletonFactory.getInstance(Page).getRequest();
		var params = request.getParams();
		this.questionID = params['qid'];
		if(this.questionID == null || this.questionID == undefined){
			var subject = SingletonFactory.getInstance(Subject);
			var request = new Request("ErrorPage","donganh",{"code":"888", "msg":"Lỗi","content":"Câu hỏi không tồn tại trong hệ thống. Mong bạn thử lại"}); 
			subject.notifyEvent('RequestRoute', request);
		}
	},
	
	getAjax: function(){
		var curPlt = this;
		var curUrl = this.root + "question/detail-question/questionid/" + this.questionID + "/page/0/rows/10";
		$.ajax({url:curUrl, async:false, success: function(ret){
			ret = $.parseJSON(ret);
			ret = ret.result;
			if(ret == undefined || ret == "error"){
				var subject = SingletonFactory.getInstance(Subject);
				var request = new Request("ErrorPage","",{"code":"888", "msg":"Lỗi","content":"Câu hỏi không tồn tại trong hệ thống. Mong bạn thử lại"}); 
				subject.notifyEvent('RequestRoute', request);
				return;
			}
			curPlt.question = ret.question;
			//curPlt.answers = ret.answers;
			
			var owner = ret.question.user_id;
			curPlt.questionOwner = owner;
			if (owner == curPlt.uid)	{
				//check if current user is the question owner
				curPlt.getAjaxAllTopics();
			}
		}});
	},
	
	getAjaxAnswer: function(){
		var curPlt = this;
		var curUrl = this.root + "question/get-question-answer/questionid/" + this.questionID + "/page/0/rows/10";
		$.ajax({url:curUrl, async:true, success: function(ret){
			ret = $.parseJSON(ret);
			ret = ret.result;
			if(ret == undefined || ret == "error"){
				var subject = SingletonFactory.getInstance(Subject);
				var request = new Request("ErrorPage","",{"code":"888", "msg":"Lỗi","content":"Câu hỏi không tồn tại trong hệ thống. Mong bạn thử lại"}); 
				subject.notifyEvent('RequestRoute', request);
				return;
			}
			curPlt.answers = ret.answers;
			curPlt.buildAnswer(ret.answers);
		}});
	},
	
	getAjaxAllTopics: function(){
		var curPlt = this;
		var curUrl = this.root + "catchword/get-all-catchwords/";
		$.ajax({url:curUrl, async:true , success: function(ret){
			ret = $.parseJSON(ret);
			ret = ret.result;
			if(ret == undefined || ret == "error"){
				//console.log("Cannot get all topic")
				return;
			}
			curPlt.topics = ret;
			//build all topic when done
			curPlt.buildAllTopics(ret);
			SingletonFactory.getInstance(Application).getSystemProperties().set("memcached.topics",ret);
		}});
	},
	
	getAjaxTopicQuestion: function(){
		var curPlt = this;
		var curUrl = this.root + "question/get-all-catchwords-question/qid/" + this.questionID;
		$.ajax({url:curUrl, async:true, success: function(ret){
			ret = $.parseJSON(ret);
			ret = ret.result;
			if(ret == undefined || ret == "error"){
				//console.log("Cannot get all topic")
				return;
			}
			curPlt.topicsQuestion = ret;
			curPlt.buildTopics(ret);
		}});
	},
	
	buildQuestion: function(){
		this.model.qcontent = this.question.title;
		this.model.qdetail = this.question.content;
		this.model.qdate = this.question.created_date;
		this.model.quser = "";
		this.model.qusertarget = "";
		if(this.question.user['name'] != undefined && this.question.user['name']!=""){
			this.quid = this.question.user['id'];
			var objParam = {};
			objParam.quserid = this.question.user['id'];
			objParam.qusername = this.question.user['name'];
			this.model.quser = tmpl("AnswerPortlet-UserLink",objParam);
		}
		
		if(this.question.target_name != undefined && this.question.target_name !=""){
			var objParam = {};
			objParam.quserid = this.question.target_id;
			objParam.qusername = this.question.target_name;
			this.model.qusertarget = tmpl("AnswerPortlet-UserLink",objParam);
		}
	},
	
	buildTopics: function(topicsQuestion){
		var result = $("<div><div></div></div>");
		var topicAdded = Array();
		for ( var key in topicsQuestion) {
			var objParam = {};
			var curObj = topicsQuestion[key];
			objParam.tid = generateId("tt");
			objParam.content = curObj['catchword'];
			objParam.cid = curObj['id'];
			objParam.uid = this.quid;
			topicAdded[curObj['id']] = objParam.tid;
			var newTp = tmpl("AnswerPortlet-Topic",objParam);
			result.children().append(newTp);
		}
		// fetch to cache
		var sysProp = SingletonFactory.getInstance(Application).getSystemProperties();
		sysProp.set("memcached.addedTopics",topicAdded);
		
		// changed to ajax oriented
		$("#question-header-topic-plhld").append(result.children().html());
		//this.model.topics = result.children();
		var sbj = SingletonFactory.getInstance(Subject);
		sbj.notifyEvent("CheckTopicEditable");
	},
	
	buildAllTopics: function(topics){
		var result = $("<div><div></div></div>");
		for ( var key in topics) {
			var curObj = topics[key];
			var newTp = $("<option value='"+curObj['id']+"'>"+curObj['catchWord']+"</option>")
			result.children().append(newTp);
		}
		
		// changed to ajax oriented
		$("#bkp-topic-list").append(result.children().html());
		//this.model.avaiTopics = result.children();
	},

	buildAnswer : function(answers) {
		var result = $("<div></div>");
		var checkUserAnswered = Array();
		for ( var key in answers) {
			this.answerNum ++;
			var objParam = {};
			var curObj = answers[key];
			objParam.uid = curObj['userID'];
			checkUserAnswered.push(curObj['userID']);
			// TODO: neu uid == this user => no need for mce
			if(curObj['userID'] == this.uid){
				this.needMCE = false;
			}
			objParam.aid = curObj['id'];
			objParam.uimglink = curObj['user'].avatar;
			objParam.uname= curObj['user'].name;
			objParam.avote = curObj['vote'];
			objParam.adate = curObj['created_date'];
			objParam.acontent = curObj['content'];
			var template = $(tmpl("AnswerPortlet-Item", objParam));
			result.append($(template).html());
		}
		
		// Used in plugin
		SingletonFactory.getInstance(Application).getSystemProperties().set("memcached.answeredID",checkUserAnswered);
		$("#answer-list").append($(result).html());
		
		var sbj = SingletonFactory.getInstance(Subject);
		var checkImg = {};
		checkImg.zone = $("#answer-list");
		sbj.notifyEvent("RequestProfileImageCheck", checkImg);
		
		this.buildEditor();
		this.updateAnswerNum();
		var curID = SingletonFactory.getInstance(Application).getSystemProperties().get("user.id") || -1;
		curID = "answer-createnew-" + curID;
		sbj.notifyEvent("BindingChangeAnswer");
		sbj.notifyEvent("TinyEditorInit",{id : curID, content: ""});
		//sbj.notifyEvent("EditorCreateInstance",{id : curID, content: ""});
		//this.model.children = $(result).children();
		var qid = this.getRequest().getParam('qid');
		sbj.notifyEvent("ShowBio", {'qid': qid});
		sbj.notifyEvent("RenderBioEditLink", {'qid': qid});
		//clean style
		sbj.notifyEvent('CleanFont');
	},
	
	buildEditor: function(){
		var objParam = {};
		objParam.uid = SingletonFactory.getInstance(Application).getSystemProperties().get("user.id") || -1;;
		if(!this.needMCE){
			objParam.style = "display:none";
			objParam.addNew = "return false;";
		} else {
			//console.log("Need MCE");
			objParam.style = "";
			objParam.addNew = "generateEvent(&apos;SubmitAnswer&apos;,{id:&apos;answer-createnew-"+objParam.uid+"&apos;, uid:&apos;"+objParam.uid+"&apos;, pid:&apos;bkp-answer-new-plhld&apos;})";
		}
		
		var mce = $(tmpl("AnswerPortlet-MCE",objParam));
		$("#bkp-answer-new-plhld").append(mce.html());
		//this.model.mce = mce;
	},
	
	buildQuestionVote: function(){
		var result = null;
		var curUrl = this.root + "question/get-question-vote";
		$.ajax({url:curUrl, async:true , data: {qid: this.questionID}, type: "POST", success: function(ret){
			ret = $.parseJSON(ret);
			ret = ret.result;
			if(ret == undefined || ret == "error"){
				//console.log("Cannot get all topic")
				return;
			}
			result = ret;
			
			//changed to ajax oriented
			$("#bkp_q_vote_up").html(ret['up']);
			$("#bkp_q_vote_down").html(ret['down']);
		}});
		//this.model.qvoteup = result['up'];
		//this.model.qvotedown = result['down'];
	},
	
	updateAnswerNum: function(){
		// update count
		var countPage = parseInt($("#answer-more-btn").attr("page"));
		var sum = this.answerNum + countPage;
		$("#answer-more-btn").attr("page",sum);
	},
	

	run : function() {
		this.getAjax();
		this.buildQuestion();
		
		this.getPortletPlaceholder().paintCanvas(this.render());
		if (this.questionOwner != this.uid)	{
			this.requestForEffectiveResource('ChangeTopic').hide();
		}
		
		this.getAjaxAnswer();
		
		this.getAjaxTopicQuestion();
		this.buildQuestionVote();
	},
	
	onReloadPage: function(){
		this.init();
		this.onBegin();
		this.run();
	},
	
	onEnd: function()	{
		this.unregisterObserver();
	}
}).implement(RenderInterface).implement(PortletInterface).implement(
		ObserverInterface);

/**
 * 
 */

NotificationBriefPortlet = Class.extend(
		{
			init : function() {
				this.name = "NotificationBriefPortlet";
				this.intervalID = 0;
			},
			
			onBegin: function()	{
				this.registerObserver();
			},
			
			onNotifBriefButtonClick: function()	{
				var subject = SingletonFactory.getInstance(Subject);
				var request = new Request("NotificationFull",undefined,null); 
				subject.notifyEvent('RequestRoute', request); 
			},

			setInterval : function() {
				this.intervalID = setInterval(this.doAjax, 1000);
			},

			doAjax : function() {
				var app = SingletonFactory.getInstance(Application);
				var root = app.getSystemProperties().get("host.root");
				var currentNotifID = app.getSystemProperties().get("notification.maxNotiID");
				if(currentNotifID === undefined){
					currentNotifID = 0;
				}

				// get notification
				// FIXME: get userid here
				$.get(root + "ajax/get-live-notification/", {},
						function(ret) {
							// {"id":"2","result":{"1":{"id":"1","name":"B\u00e9
							// Heo"},"5":{"id":"2","name":"Minhthedt
							// Thedaica"}}}
							ret = $.parseJSON(ret);
							ret = ret.result;
							if (currentNotifID == ret.id){
								return;
							}
							
							if(ret.num == 0) {
								//clear and return
								var subject = SingletonFactory.getInstance(Subject);
								subject.notifyEvent("NotificateClear", ret);
								return;
							}
							var currentNotifID = ret.num;
							app.getSystemProperties().set("notification.maxNotiID", currentNotifID);
							ret = ret.result;
							var subject = SingletonFactory.getInstance(Subject);
							subject.notifyEvent("NotificateAfterAjax", ret);
						});
			},
			
			onNotificateClear: function (){
//				this.requestForResource("notification-live").empty().hide();
			},

			onNotificateAfterAjax : function(ret) {
				var app = SingletonFactory.getInstance(Application);
				var currentNotifID = app.getSystemProperties().get("notification.maxNotiID");
				var liveNum = this.getLocalizedMessage('LiveNotification', currentNotifID);
				$("#NotificationBriefPortlet-notification-live").empty().append(liveNum).show().css("display","inline-block").css("color","red");
				
				// Định notify cho đẹp, ai dè teo
//				for ( var key in ret) {
//					var profilename = ret[key]['name'];
//					this.notification(profilename," has sent you an notification");
//				}
			},

			notification : function(from, message) {
				// initialize notification area
//				//console.log($(".ui-notification-container"));
//				$(".ui-notification-container").notification();

//				  $(".ui-notification-container").notification("create", {
//			            title: "Hello world!",
//			            content: "I am a default notification"
//			        });
			},

			run : function() {
				this.doAjax();
				this.setInterval();
				this.getPortletPlaceholder().drawToCanvas(this.render());
			},
			
			onEnd: function(){
				clearInterval(this.intervalID);
				this.unregisterObserver();
			}
		}).implement(RenderInterface).implement(PortletInterface).implement(ObserverInterface);

ViewFullNotificationHandler = Handler.extend({
	getEventName: function()	{
		return "click";
	},
	
	onEvent: function(){
		alert("donganh");
	}
});
/**
 * 
 */

NotificationFullPortlet = Class.extend(
		{
			init : function() {
				this.name = "NotificationFullPortlet";
				this.model = {};
			},

			doAjax : function() {
				var root = SingletonFactory.getInstance(Application)
						.getSystemProperties().get("host.root");
				var currentPltObj = this;
				// get notification 
				$.get(root + "ajax/get-notification-full/", {},
						function(ret) {
							ret = $.parseJSON(ret);
							ret = ret.result;
							if(ret == 'error' || ret == undefined){
								// Navigate to error page
								var subject = SingletonFactory.getInstance(Subject);
								var request = new Request("ErrorPage","donganh",{"code":"888", "msg":"Lỗi","content":"Lỗi tự tạo thôi"}); 
								subject.notifyEvent('RequestRoute', request);
							} else {
								ret = $.parseJSON(ret);
								currentPltObj.afterAjax(ret);
							}
						});
			},

			afterAjax : function(ret) {
				// {profilename:name, profilepic: pic, profileid: id, message:
				// message, detailid: detailID}
				// loop and build template
				var notifList = Array();
				var num = 0;
				for ( var i in ret) {
					var objParam = {};
					objParam.profilename = ret[i]['name'];
					objParam.profilepic = ret[i]['avatar'];
					objParam.profileid = ret[i]['id'];
					objParam.message = ret[i]['content'];
					objParam.link = this.buildLink(eval("("+ret[i]['link'] + ")"));
					objParam.detail = "";
					var template = this.renderView("NotifUnSeen", objParam);
					notifList.push(template);
					num++;
				}
				var header = this.getLocalizedMessage('NoNotif', num);
				this.model.noNotif = header;
				this.model.messageNoNotif = header;
				this.model.children = notifList;
				this.getPortletPlaceholder().drawToCanvas(this.render());
			},
			
			buildLink: function(linkJson){
				var linkResult = "";
				for ( var i in linkJson) {
					var key = i;
					var value = linkJson[key];
					if (key == 'type')	{
						key = 'page';
						if (value == 'Question')	{
							value = 'Question';
						}
					}
					linkResult += "/" + key + "/" + value;
				}
				var result = "#" + linkResult.substring(1);;
				return result;
			},

			run : function() {
				this.doAjax();
			}
		}).implement(RenderInterface).implement(PortletInterface);
/**
 * 
 */

SearcherPortlet = Class.extend({
	init:function() {
		this.name = "SearcherPortlet";
	},
	
	requestForResource: function(resourceName){
		var app = SingletonFactory.getInstance(Application);
		var rm = app.getResourceManager();
		return rm.requestForResource(this.name,resourceName);
	},
	
	run: function() {
		this.getPortletPlaceholder().drawToCanvas(this.render());
		$("#tabs").tabs();
		$("#"+this.placeholder.canvas.id).css("float","right");
	}
}).implement(RenderInterface).implement(PortletInterface);
/**
 * 
 */

TopicCreatePortlet = Class.extend(
		{
			init : function() {
				this.name = "TopicCreatePortlet";
				this.model = {};
				this.template = "";
				this.topics = null;
				this.app = SingletonFactory.getInstance(Application);
				this.root = this.app.getSystemProperties().get("host.root");
				this.addedTopics = null;
				this.topicMap = Array();
				this.topicAvaiContextCommit = Array();
				this.topicNewContextCommit = Array();
			},
			
			onBegin: function()	{
				this.registerObserver();
				this.template = $(tmpl("CommonPortlet-TopicNew",{}));
				this.prepareTopics();
			},
			
			onNewTopicAdded: function(eventData){
				var topicID = eventData.name;
				var topicDesID = eventData.des;
				
				var topicContent = $("#" + topicID).val().trim();
				var topicDes = $("#" + topicDesID).val().trim();
				
				if(topicContent == "" || topicDes == ""){
					alert("Chưa nhập đủ chủ đề và chi tiết chủ đề");
					return;
				}
				
				// đã có
				var objParam = {};
				objParam.content = topicContent;
				if(this.topicMap[objParam.content]){
					alert("Đã có chủ đề này.")
					return;
				}
				this.topicMap[objParam.content] = true;
				var template = tmpl("CommonPortlet-Topic",objParam);
				$("#commonCreatedTopics").append(template);
				objParam = {};
				objParam.topicName = topicContent;
				objParam.topicDes = topicDes;
				this.topicAvaiContextCommit.push(objParam);
			
				// reset
				$("#" + topicID).val("");
				$("#" + topicDesID).val("");
			},
			
			prepareTopics: function(){
				if(SingletonFactory.getInstance(Application).getSystemProperties().get("memcached.topics") == undefined){
					this.getAjaxAllTopics();
				}
			},
			
			getAjaxAllTopics: function(){
				var curPlt = this;
				var curUrl = this.root + "catchword/get-all-catchwords/";
				$.ajax({url:curUrl, async:true, data:{}, success: function(ret){
					ret = $.parseJSON(ret);
					ret = ret.result;
					if(ret == undefined || ret == "error"){
						//console.log("Cannot get all topic")
						return;
					}
					curPlt.preparedAvaiTopics (ret);
					curPlt.topics = ret;
					SingletonFactory.getInstance(Application).getSystemProperties().set("memcached.topics",ret);
				}});
				this.topics = curPlt.topics;
			},
			
			preparedAvaiTopics: function(arr){
				for ( var key in arr) {
					var curObj = arr[key];
					content = curObj['catchWord'];
					this.topicMap[content] = true;
				}
			},
			
			buildTopics: function(arr){
				var result = $("<div><div></div></div>");
				for ( var key in arr) {
					var curObj = arr[key];
					var newTp = $("<option value='"+curObj['id']+"'>"+curObj['catchWord']+"</option>");
					result.children().append(newTp);
				}
				return result.children();
			},
			
			onNewTopicConfirmed: function(){
				var curPlt = this;
				this.numCount = this.topicAvaiContextCommit.length;
				this.done = 0;
				for(var key in this.topicAvaiContextCommit){
					var curObj = this.topicAvaiContextCommit[key]; 
					var curUrl = this.root + "catchword/add-new-topic";
					var sbj = SingletonFactory.getInstance(Subject);
					$.ajax({url:curUrl, data: curObj, success: function(ret){
						ret = $.parseJSON(ret);
						if(!isNaN(ret.result)){
							curPlt.done++;
							sbj.notifyEvent("NotifyGlobal","Thêm thành công");
							sbj.notifyEvent("CommitTopicSuccess", {'value': ret.result, 'txt':curObj.topicName});
						}
						//curPlt.buildLocalTopic({text: curObj.topicName, value: curObj.topicName+curObj.contextName});
					}, error: function(){
						sbj.notifyEvent("NotifyGlobal","Thêm thất bại");
					}});
				}
			},
			
			onCommitTopicSuccess: function()	{
				if(this.done < this.numCount){
					return;
				}
				var sbj = SingletonFactory.getInstance(Subject);
				var rq = SingletonFactory.getInstance(Page).getRequest();
				var params = rq.getParams();
				var page = params["pageCallBack"] || "Home";
				var needParam = params["needParam"] || {};
				var paramVal = params["paramVal"] || null;
				var paramName = params["paramName"] || null;
				var request = null;
					
				if(eval(needParam)){
					if(paramVal != null && paramName!= null){
						var obj = {};
						obj[paramName] = paramVal;
						request = new Request(page,"",obj);
					} else {
						request = new Request(page,"",{});
					}
				} else {
					request = new Request("Home","",{});
				}

				sbj.notifyEvent('RequestRoute', request);
			},
			
			run : function() {
				this.getPortletPlaceholder().drawToCanvas(this.template);
			},
			
			onEnd: function()	{
				this.unregisterObserver();
			}
		}).implement(RenderInterface).implement(PortletInterface).implement(ObserverInterface);


TopicCreatePortletStandalone = TopicCreatePortlet.extend({
	init: function()	{
		this._super();
		this.name = "TopicCreatePortletStandalone";
	},
	
	onCommitTopicSuccess: function(eventData)	{
		var commitCb = this.getRequest().getParam('commit-callback');
		window.opener.generateEvent(commitCb, eventData);
		
		if (this.done < this.numCount)
			return;
		var cb = this.getRequest().getParam('callback');
		window.opener.generateEvent(cb);
		self.close();
	}
}).implement(PortletInterface).implement(RenderInterface).implement(ObserverInterface);

HideLayoutPlugin = Class.extend({
	init: function()	{
		this.name = "HideLayoutPlugin";
	},
	
	onHtmlRendered: function()	{
		$('#bkp_top').hide();
		$('#bkp_middle_content').attr('style', 'width: 600px');
		$('#bkp_middle').attr('style', 'width: 600px');
		$('#bkp_middle_nav').hide();
		$('#bkp_bottom').hide();
		$('#bkp_middle_top').hide();
		$('#bkp_middle_left').hide();
		$('#bkp_middle_right').hide();
	}
}).implement(PluginInterface);
//Fix bug in IE
if (typeof String.prototype.trim !== 'function') {
	String.prototype.trim = function() {
		return this.replace(/^\s+|\s+$/g, "");
	};
}
if (typeof Array.prototype.indexOf !== 'function') {
	Array.prototype.indexOf = function(obj) {
		for ( var i = 0; i < this.length; i++) {
			if (this[i] == obj) {
				return i;
			}
		}
		return -1;
	};
}
if (!window['google']) {
window['google'] = {};
}
if (!window['google']['loader']) {
window['google']['loader'] = {};
google.loader.ServiceBase = 'http://www.google.com/uds';
google.loader.GoogleApisBase = 'http://ajax.googleapis.com/ajax';
google.loader.ApiKey = 'notsupplied';
google.loader.KeyVerified = true;
google.loader.LoadFailure = false;
google.loader.Secure = false;
google.loader.GoogleLocale = 'www.google.com';
google.loader.ClientLocation = {"latitude":21.017,"longitude":105.867,"address":{"city":"","region":"Ha Noi","country":"Vietnam","country_code":"VN"}};
google.loader.AdditionalParams = '';
(function() {var d=void 0,g=null,h=encodeURIComponent,j=window,k=document;function l(a,b){return a.load=b}var m="push",o="replace",p="charAt",r="indexOf",s="ServiceBase",t="name",u="getTime",v="length",w="prototype",x="setTimeout",y="loader",z="substring",A="join",B="toLowerCase";function C(a){if(a in D)return D[a];return D[a]=navigator.userAgent[B]()[r](a)!=-1}var D={};function E(a,b){var c=function(){};c.prototype=b[w];a.S=b[w];a.prototype=new c}
function F(a,b){var c=Array[w].slice.call(arguments,2)||[];return function(){var e=c.concat(Array[w].slice.call(arguments));return a.apply(b,e)}}function G(a){a=Error(a);a.toString=function(){return this.message};return a}function H(a,b){for(var c=a.split(/\./),e=j,f=0;f<c[v]-1;f++)e[c[f]]||(e[c[f]]={}),e=e[c[f]];e[c[c[v]-1]]=b}function I(a,b,c){a[b]=c}if(!J)var J=H;if(!K)var K=I;google[y].v={};J("google.loader.callbacks",google[y].v);var L={},M={};google[y].eval={};J("google.loader.eval",google[y].eval);
l(google,function(a,b,c){function e(a){var b=a.split(".");if(b[v]>2)throw G("Module: '"+a+"' not found!");else if(typeof b[1]!="undefined")f=b[0],c.packages=c.packages||[],c.packages[m](b[1])}var f=a,c=c||{};if(a instanceof Array||a&&typeof a=="object"&&typeof a[A]=="function"&&typeof a.reverse=="function")for(var i=0;i<a[v];i++)e(a[i]);else e(a);if(a=L[":"+f]){c&&!c.language&&c.locale&&(c.language=c.locale);if(c&&typeof c.callback=="string"&&(i=c.callback,i.match(/^[[\]A-Za-z0-9._]+$/)))i=j.eval(i),
c.callback=i;if((i=c&&c.callback!=g)&&!a.s(b))throw G("Module: '"+f+"' must be loaded before DOM onLoad!");else i?a.m(b,c)?j[x](c.callback,0):a.load(b,c):a.m(b,c)||a.load(b,c)}else throw G("Module: '"+f+"' not found!");});J("google.load",google.load);
google.R=function(a,b){b?(N[v]==0&&(O(j,"load",P),!C("msie")&&!C("safari")&&!C("konqueror")&&C("mozilla")||j.opera?j.addEventListener("DOMContentLoaded",P,!1):C("msie")?k.write("<script defer onreadystatechange='google.loader.domReady()' src=//:><\/script>"):(C("safari")||C("konqueror"))&&j[x](R,10)),N[m](a)):O(j,"load",a)};J("google.setOnLoadCallback",google.R);
function O(a,b,c){if(a.addEventListener)a.addEventListener(b,c,!1);else if(a.attachEvent)a.attachEvent("on"+b,c);else{var e=a["on"+b];a["on"+b]=e!=g?aa([c,e]):c}}function aa(a){return function(){for(var b=0;b<a[v];b++)a[b]()}}var N=[];google[y].N=function(){var a=j.event.srcElement;if(a.readyState=="complete")a.onreadystatechange=g,a.parentNode.removeChild(a),P()};J("google.loader.domReady",google[y].N);var ba={loaded:!0,complete:!0};function R(){ba[k.readyState]?P():N[v]>0&&j[x](R,10)}
function P(){for(var a=0;a<N[v];a++)N[a]();N.length=0}google[y].d=function(a,b,c){if(c){var e;if(a=="script")e=k.createElement("script"),e.type="text/javascript",e.src=b;else if(a=="css")e=k.createElement("link"),e.type="text/css",e.href=b,e.rel="stylesheet";(a=k.getElementsByTagName("head")[0])||(a=k.body.parentNode.appendChild(k.createElement("head")));a.appendChild(e)}else a=="script"?k.write('<script src="'+b+'" type="text/javascript"><\/script>'):a=="css"&&k.write('<link href="'+b+'" type="text/css" rel="stylesheet"></link>')};
J("google.loader.writeLoadTag",google[y].d);google[y].O=function(a){M=a};J("google.loader.rfm",google[y].O);google[y].Q=function(a){for(var b in a)typeof b=="string"&&b&&b[p](0)==":"&&!L[b]&&(L[b]=new S(b[z](1),a[b]))};J("google.loader.rpl",google[y].Q);google[y].P=function(a){if((a=a.specs)&&a[v])for(var b=0;b<a[v];++b){var c=a[b];typeof c=="string"?L[":"+c]=new T(c):(c=new U(c[t],c.baseSpec,c.customSpecs),L[":"+c[t]]=c)}};J("google.loader.rm",google[y].P);google[y].loaded=function(a){L[":"+a.module].l(a)};
J("google.loader.loaded",google[y].loaded);google[y].M=function(){return"qid="+((new Date)[u]().toString(16)+Math.floor(Math.random()*1E7).toString(16))};J("google.loader.createGuidArg_",google[y].M);H("google_exportSymbol",H);H("google_exportProperty",I);google[y].b={};J("google.loader.themes",google[y].b);google[y].b.H="//www.google.com/cse/style/look/bubblegum.css";K(google[y].b,"BUBBLEGUM",google[y].b.H);google[y].b.J="//www.google.com/cse/style/look/greensky.css";K(google[y].b,"GREENSKY",google[y].b.J);
google[y].b.I="//www.google.com/cse/style/look/espresso.css";K(google[y].b,"ESPRESSO",google[y].b.I);google[y].b.L="//www.google.com/cse/style/look/shiny.css";K(google[y].b,"SHINY",google[y].b.L);google[y].b.K="//www.google.com/cse/style/look/minimalist.css";K(google[y].b,"MINIMALIST",google[y].b.K);function T(a){this.a=a;this.o=[];this.n={};this.e={};this.f={};this.j=!0;this.c=-1}
T[w].g=function(a,b){var c="";b!=d&&(b.language!=d&&(c+="&hl="+h(b.language)),b.nocss!=d&&(c+="&output="+h("nocss="+b.nocss)),b.nooldnames!=d&&(c+="&nooldnames="+h(b.nooldnames)),b.packages!=d&&(c+="&packages="+h(b.packages)),b.callback!=g&&(c+="&async=2"),b.style!=d&&(c+="&style="+h(b.style)),b.other_params!=d&&(c+="&"+b.other_params));if(!this.j){google[this.a]&&google[this.a].JSHash&&(c+="&sig="+h(google[this.a].JSHash));var e=[],f;for(f in this.n)f[p](0)==":"&&e[m](f[z](1));for(f in this.e)f[p](0)==
":"&&this.e[f]&&e[m](f[z](1));c+="&have="+h(e[A](","))}return google[y][s]+"/?file="+this.a+"&v="+a+google[y].AdditionalParams+c};T[w].t=function(a){var b=g;a&&(b=a.packages);var c=g;if(b)if(typeof b=="string")c=[a.packages];else if(b[v]){c=[];for(a=0;a<b[v];a++)typeof b[a]=="string"&&c[m](b[a][o](/^\s*|\s*$/,"")[B]())}c||(c=["default"]);b=[];for(a=0;a<c[v];a++)this.n[":"+c[a]]||b[m](c[a]);return b};
l(T[w],function(a,b){var c=this.t(b),e=b&&b.callback!=g;if(e)var f=new V(b.callback);for(var i=[],n=c[v]-1;n>=0;n--){var q=c[n];e&&f.A(q);if(this.e[":"+q])c.splice(n,1),e&&this.f[":"+q][m](f);else i[m](q)}if(c[v]){b&&b.packages&&(b.packages=c.sort()[A](","));for(n=0;n<i[v];n++)q=i[n],this.f[":"+q]=[],e&&this.f[":"+q][m](f);if(!b&&M[":"+this.a]!=g&&M[":"+this.a].versions[":"+a]!=g&&!google[y].AdditionalParams&&this.j){c=M[":"+this.a];google[this.a]=google[this.a]||{};for(var Q in c.properties)Q&&Q[p](0)==
":"&&(google[this.a][Q[z](1)]=c.properties[Q]);google[y].d("script",google[y][s]+c.path+c.js,e);c.css&&google[y].d("css",google[y][s]+c.path+c.css,e)}else(!b||!b.autoloaded)&&google[y].d("script",this.g(a,b),e);if(this.j&&(this.j=!1,this.c=(new Date)[u](),this.c%100!=1))this.c=-1;for(n=0;n<i[v];n++)q=i[n],this.e[":"+q]=!0}});
T[w].l=function(a){if(this.c!=-1)W("al_"+this.a,"jl."+((new Date)[u]()-this.c),!0),this.c=-1;this.o=this.o.concat(a.components);google[y][this.a]||(google[y][this.a]={});google[y][this.a].packages=this.o.slice(0);for(var b=0;b<a.components[v];b++){this.n[":"+a.components[b]]=!0;this.e[":"+a.components[b]]=!1;var c=this.f[":"+a.components[b]];if(c){for(var e=0;e<c[v];e++)c[e].B(a.components[b]);delete this.f[":"+a.components[b]]}}};T[w].m=function(a,b){return this.t(b)[v]==0};T[w].s=function(){return!0};
function V(a){this.D=a;this.q={};this.r=0}V[w].A=function(a){this.r++;this.q[":"+a]=!0};V[w].B=function(a){this.q[":"+a]&&(this.q[":"+a]=!1,this.r--,this.r==0&&j[x](this.D,0))};function U(a,b,c){this.name=a;this.C=b;this.p=c;this.u=this.h=!1;this.k=[];google[y].v[this[t]]=F(this.l,this)}E(U,T);l(U[w],function(a,b){var c=b&&b.callback!=g;c?(this.k[m](b.callback),b.callback="google.loader.callbacks."+this[t]):this.h=!0;(!b||!b.autoloaded)&&google[y].d("script",this.g(a,b),c)});U[w].m=function(a,b){return b&&b.callback!=g?this.u:this.h};U[w].l=function(){this.u=!0;for(var a=0;a<this.k[v];a++)j[x](this.k[a],0);this.k=[]};
var X=function(a,b){return a.string?h(a.string)+"="+h(b):a.regex?b[o](/(^.*$)/,a.regex):""};U[w].g=function(a,b){return this.F(this.w(a),a,b)};
U[w].F=function(a,b,c){var e="";a.key&&(e+="&"+X(a.key,google[y].ApiKey));a.version&&(e+="&"+X(a.version,b));b=google[y].Secure&&a.ssl?a.ssl:a.uri;if(c!=g)for(var f in c)a.params[f]?e+="&"+X(a.params[f],c[f]):f=="other_params"?e+="&"+c[f]:f=="base_domain"&&(b="http://"+c[f]+a.uri[z](a.uri[r]("/",7)));google[this[t]]={};b[r]("?")==-1&&e&&(e="?"+e[z](1));return b+e};U[w].s=function(a){return this.w(a).deferred};U[w].w=function(a){if(this.p)for(var b=0;b<this.p[v];++b){var c=this.p[b];if(RegExp(c.pattern).test(a))return c}return this.C};function S(a,b){this.a=a;this.i=b;this.h=!1}E(S,T);l(S[w],function(a,b){this.h=!0;google[y].d("script",this.g(a,b),!1)});S[w].m=function(){return this.h};S[w].l=function(){};S[w].g=function(a,b){if(!this.i.versions[":"+a]){if(this.i.aliases){var c=this.i.aliases[":"+a];c&&(a=c)}if(!this.i.versions[":"+a])throw G("Module: '"+this.a+"' with version '"+a+"' not found!");}return google[y].GoogleApisBase+"/libs/"+this.a+"/"+a+"/"+this.i.versions[":"+a][b&&b.uncompressed?"uncompressed":"compressed"]};
S[w].s=function(){return!1};var Y=!1,Z=[],ca=(new Date)[u](),W=function(a,b,c){Y||(O(j,"unload",da),Y=!0);if(c){if(!google[y].Secure&&(!google[y].Options||google[y].Options.csi===!1))a=a[B]()[o](/[^a-z0-9_.]+/g,"_"),b=b[B]()[o](/[^a-z0-9_.]+/g,"_"),j[x](F($,g,"//gg.google.com/csi?s=uds&v=2&action="+h(a)+"&it="+h(b)),1E4)}else Z[m]("r"+Z[v]+"="+h(a+(b?"|"+b:""))),j[x](da,Z[v]>5?0:15E3)},da=function(){if(Z[v]){var a=google[y][s];a[r]("http:")==0&&(a=a[o](/^http:/,"https:"));$(a+"/stats?"+Z[A]("&")+"&nc="+(new Date)[u]()+"_"+((new Date)[u]()-
ca));Z.length=0}},$=function(a){var b=new Image,c=$.G++;$.z[c]=b;b.onload=b.onerror=function(){delete $.z[c]};b.src=a;b=g};$.z={};$.G=0;H("google.loader.recordStat",W);H("google.loader.createImageForLogging",$);

}) ();google.loader.rm({"specs":[{"name":"books","baseSpec":{"uri":"http://books.google.com/books/api.js","ssl":null,"key":{"string":"key"},"version":{"string":"v"},"deferred":true,"params":{"callback":{"string":"callback"},"language":{"string":"hl"}}}},"feeds",{"name":"friendconnect","baseSpec":{"uri":"http://www.google.com/friendconnect/script/friendconnect.js","ssl":null,"key":{"string":"key"},"version":{"string":"v"},"deferred":false,"params":{}}},"spreadsheets","identitytoolkit","gdata","visualization",{"name":"sharing","baseSpec":{"uri":"http://www.google.com/s2/sharing/js","ssl":null,"key":{"string":"key"},"version":{"string":"v"},"deferred":false,"params":{"language":{"string":"hl"}}}},"search",{"name":"maps","baseSpec":{"uri":"http://maps.google.com/maps?file\u003dgoogleapi","ssl":"https://maps-api-ssl.google.com/maps?file\u003dgoogleapi","key":{"string":"key"},"version":{"string":"v"},"deferred":true,"params":{"callback":{"regex":"callback\u003d$1\u0026async\u003d2"},"language":{"string":"hl"}}},"customSpecs":[{"uri":"http://maps.google.com/maps/api/js","ssl":"https://maps-api-ssl.google.com/maps/api/js","key":{"string":"key"},"version":{"string":"v"},"deferred":true,"params":{"callback":{"string":"callback"},"language":{"string":"hl"}},"pattern":"^(3|3..*)$"}]},"annotations_v2","wave","orkut",{"name":"annotations","baseSpec":{"uri":"http://www.google.com/reviews/scripts/annotations_bootstrap.js","ssl":null,"key":{"string":"key"},"version":{"string":"v"},"deferred":true,"params":{"callback":{"string":"callback"},"language":{"string":"hl"},"country":{"string":"gl"}}}},"language","earth","ads","elements"]});
google.loader.rfm({":search":{"versions":{":1":"1",":1.0":"1"},"path":"/api/search/1.0/da11a17ee21435ab38fe3d34c57b4e8b/","js":"default+en.I.js","css":"default.css","properties":{":JSHash":"da11a17ee21435ab38fe3d34c57b4e8b",":NoOldNames":false,":Version":"1.0"}},":language":{"versions":{":1":"1",":1.0":"1"},"path":"/api/language/1.0/4c799b5d9590782ad04064fdda233029/","js":"default+en.I.js","properties":{":JSHash":"4c799b5d9590782ad04064fdda233029",":Version":"1.0"}},":feeds":{"versions":{":1":"1",":1.0":"1"},"path":"/api/feeds/1.0/ebcc20169bc505865931499d7e9dca8d/","js":"default+en.I.js","css":"default.css","properties":{":JSHash":"ebcc20169bc505865931499d7e9dca8d",":Version":"1.0"}},":spreadsheets":{"versions":{":0":"1",":0.4":"1"},"path":"/api/spreadsheets/0.4/87ff7219e9f8a8164006cbf28d5e911a/","js":"default.I.js","properties":{":JSHash":"87ff7219e9f8a8164006cbf28d5e911a",":Version":"0.4"}},":wave":{"versions":{":1":"1",":1.0":"1"},"path":"/api/wave/1.0/3b6f7573ff78da6602dda5e09c9025bf/","js":"default.I.js","properties":{":JSHash":"3b6f7573ff78da6602dda5e09c9025bf",":Version":"1.0"}},":earth":{"versions":{":1":"1",":1.0":"1"},"path":"/api/earth/1.0/a53f4e87830de2a72937039b5507ebdc/","js":"default.I.js","properties":{":JSHash":"a53f4e87830de2a72937039b5507ebdc",":Version":"1.0"}},":annotations":{"versions":{":1":"1",":1.0":"1"},"path":"/api/annotations/1.0/dfca8805c4b6dacbd463750331da710e/","js":"default+en.I.js","properties":{":JSHash":"dfca8805c4b6dacbd463750331da710e",":Version":"1.0"}},":picker":{"versions":{":1":"1",":1.0":"1"},"path":"/api/picker/1.0/77d23be1d9a7f6c7632cb056f3de7c8a/","js":"default.I.js","css":"default.css","properties":{":JSHash":"77d23be1d9a7f6c7632cb056f3de7c8a",":Version":"1.0"}}});
google.loader.rpl({":scriptaculous":{"versions":{":1.8.3":{"uncompressed":"scriptaculous.js","compressed":"scriptaculous.js"},":1.8.2":{"uncompressed":"scriptaculous.js","compressed":"scriptaculous.js"},":1.8.1":{"uncompressed":"scriptaculous.js","compressed":"scriptaculous.js"}},"aliases":{":1.8":"1.8.3",":1":"1.8.3"}},":yui":{"versions":{":2.6.0":{"uncompressed":"build/yuiloader/yuiloader.js","compressed":"build/yuiloader/yuiloader-min.js"},":2.9.0":{"uncompressed":"build/yuiloader/yuiloader.js","compressed":"build/yuiloader/yuiloader-min.js"},":2.7.0":{"uncompressed":"build/yuiloader/yuiloader.js","compressed":"build/yuiloader/yuiloader-min.js"},":2.8.0r4":{"uncompressed":"build/yuiloader/yuiloader.js","compressed":"build/yuiloader/yuiloader-min.js"},":2.8.2r1":{"uncompressed":"build/yuiloader/yuiloader.js","compressed":"build/yuiloader/yuiloader-min.js"},":2.8.1":{"uncompressed":"build/yuiloader/yuiloader.js","compressed":"build/yuiloader/yuiloader-min.js"},":3.3.0":{"uncompressed":"build/yui/yui.js","compressed":"build/yui/yui-min.js"}},"aliases":{":3":"3.3.0",":2":"2.9.0",":2.7":"2.7.0",":2.8.2":"2.8.2r1",":2.6":"2.6.0",":2.9":"2.9.0",":2.8":"2.8.2r1",":2.8.0":"2.8.0r4",":3.3":"3.3.0"}},":swfobject":{"versions":{":2.1":{"uncompressed":"swfobject_src.js","compressed":"swfobject.js"},":2.2":{"uncompressed":"swfobject_src.js","compressed":"swfobject.js"}},"aliases":{":2":"2.2"}},":webfont":{"versions":{":1.0.2":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.1":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.0":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.6":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.19":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.5":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.18":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.17":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.4":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.16":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.3":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.9":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.12":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.13":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.14":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.15":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.10":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.11":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"}},"aliases":{":1":"1.0.19",":1.0":"1.0.19"}},":ext-core":{"versions":{":3.1.0":{"uncompressed":"ext-core-debug.js","compressed":"ext-core.js"},":3.0.0":{"uncompressed":"ext-core-debug.js","compressed":"ext-core.js"}},"aliases":{":3":"3.1.0",":3.0":"3.0.0",":3.1":"3.1.0"}},":mootools":{"versions":{":1.2.3":{"uncompressed":"mootools.js","compressed":"mootools-yui-compressed.js"},":1.3.1":{"uncompressed":"mootools.js","compressed":"mootools-yui-compressed.js"},":1.1.1":{"uncompressed":"mootools.js","compressed":"mootools-yui-compressed.js"},":1.2.4":{"uncompressed":"mootools.js","compressed":"mootools-yui-compressed.js"},":1.3.0":{"uncompressed":"mootools.js","compressed":"mootools-yui-compressed.js"},":1.2.1":{"uncompressed":"mootools.js","compressed":"mootools-yui-compressed.js"},":1.2.2":{"uncompressed":"mootools.js","compressed":"mootools-yui-compressed.js"},":1.2.5":{"uncompressed":"mootools.js","compressed":"mootools-yui-compressed.js"},":1.1.2":{"uncompressed":"mootools.js","compressed":"mootools-yui-compressed.js"}},"aliases":{":1":"1.1.2",":1.11":"1.1.1",":1.3":"1.3.1",":1.2":"1.2.5",":1.1":"1.1.2"}},":jqueryui":{"versions":{":1.6.0":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.8.0":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.8.2":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.8.1":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.8.9":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.8.7":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.8.8":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.8.12":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.8.5":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.8.11":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.7.2":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.8.6":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.8.10":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.7.3":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.7.0":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.7.1":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.8.4":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.5.3":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.5.2":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"}},"aliases":{":1.8":"1.8.12",":1.7":"1.7.3",":1.6":"1.6.0",":1":"1.8.12",":1.5":"1.5.3",":1.8.3":"1.8.4"}},":chrome-frame":{"versions":{":1.0.2":{"uncompressed":"CFInstall.js","compressed":"CFInstall.min.js"},":1.0.1":{"uncompressed":"CFInstall.js","compressed":"CFInstall.min.js"},":1.0.0":{"uncompressed":"CFInstall.js","compressed":"CFInstall.min.js"}},"aliases":{":1":"1.0.2",":1.0":"1.0.2"}},":jquery":{"versions":{":1.3.1":{"uncompressed":"jquery.js","compressed":"jquery.min.js"},":1.3.0":{"uncompressed":"jquery.js","compressed":"jquery.min.js"},":1.3.2":{"uncompressed":"jquery.js","compressed":"jquery.min.js"},":1.2.3":{"uncompressed":"jquery.js","compressed":"jquery.min.js"},":1.2.6":{"uncompressed":"jquery.js","compressed":"jquery.min.js"},":1.4.3":{"uncompressed":"jquery.js","compressed":"jquery.min.js"},":1.4.4":{"uncompressed":"jquery.js","compressed":"jquery.min.js"},":1.5.1":{"uncompressed":"jquery.js","compressed":"jquery.min.js"},":1.5.0":{"uncompressed":"jquery.js","compressed":"jquery.min.js"},":1.4.0":{"uncompressed":"jquery.js","compressed":"jquery.min.js"},":1.5.2":{"uncompressed":"jquery.js","compressed":"jquery.min.js"},":1.4.1":{"uncompressed":"jquery.js","compressed":"jquery.min.js"},":1.4.2":{"uncompressed":"jquery.js","compressed":"jquery.min.js"}},"aliases":{":1":"1.5.2",":1.5":"1.5.2",":1.4":"1.4.4",":1.3":"1.3.2",":1.2":"1.2.6"}},":prototype":{"versions":{":1.7.0.0":{"uncompressed":"prototype.js","compressed":"prototype.js"},":1.6.0.2":{"uncompressed":"prototype.js","compressed":"prototype.js"},":1.6.1.0":{"uncompressed":"prototype.js","compressed":"prototype.js"},":1.6.0.3":{"uncompressed":"prototype.js","compressed":"prototype.js"}},"aliases":{":1.7":"1.7.0.0",":1.6.1":"1.6.1.0",":1":"1.7.0.0",":1.6":"1.6.1.0",":1.7.0":"1.7.0.0",":1.6.0":"1.6.0.3"}},":dojo":{"versions":{":1.2.3":{"uncompressed":"dojo/dojo.xd.js.uncompressed.js","compressed":"dojo/dojo.xd.js"},":1.3.1":{"uncompressed":"dojo/dojo.xd.js.uncompressed.js","compressed":"dojo/dojo.xd.js"},":1.1.1":{"uncompressed":"dojo/dojo.xd.js.uncompressed.js","compressed":"dojo/dojo.xd.js"},":1.3.0":{"uncompressed":"dojo/dojo.xd.js.uncompressed.js","compressed":"dojo/dojo.xd.js"},":1.3.2":{"uncompressed":"dojo/dojo.xd.js.uncompressed.js","compressed":"dojo/dojo.xd.js"},":1.6.0":{"uncompressed":"dojo/dojo.xd.js.uncompressed.js","compressed":"dojo/dojo.xd.js"},":1.4.3":{"uncompressed":"dojo/dojo.xd.js.uncompressed.js","compressed":"dojo/dojo.xd.js"},":1.5.1":{"uncompressed":"dojo/dojo.xd.js.uncompressed.js","compressed":"dojo/dojo.xd.js"},":1.5.0":{"uncompressed":"dojo/dojo.xd.js.uncompressed.js","compressed":"dojo/dojo.xd.js"},":1.2.0":{"uncompressed":"dojo/dojo.xd.js.uncompressed.js","compressed":"dojo/dojo.xd.js"},":1.4.0":{"uncompressed":"dojo/dojo.xd.js.uncompressed.js","compressed":"dojo/dojo.xd.js"},":1.4.1":{"uncompressed":"dojo/dojo.xd.js.uncompressed.js","compressed":"dojo/dojo.xd.js"}},"aliases":{":1":"1.6.0",":1.6":"1.6.0",":1.5":"1.5.1",":1.4":"1.4.3",":1.3":"1.3.2",":1.2":"1.2.3",":1.1":"1.1.1"}}});
}

if (!window['google']) {
window['google'] = {};
}
if (!window['google']['loader']) {
window['google']['loader'] = {};
google.loader.ServiceBase = 'http://www.google.com/uds';
google.loader.GoogleApisBase = 'http://ajax.googleapis.com/ajax';
google.loader.ApiKey = 'notsupplied';
google.loader.KeyVerified = true;
google.loader.LoadFailure = false;
google.loader.Secure = false;
google.loader.GoogleLocale = 'www.google.com';
google.loader.ClientLocation = {"latitude":21.017,"longitude":105.867,"address":{"city":"","region":"Ha Noi","country":"Vietnam","country_code":"VN"}};
google.loader.AdditionalParams = '';
(function() {var d=void 0,g=null,h=encodeURIComponent,j=window,k=document;function l(a,b){return a.load=b}var m="push",o="replace",p="charAt",r="indexOf",s="ServiceBase",t="name",u="getTime",v="length",w="prototype",x="setTimeout",y="loader",z="substring",A="join",B="toLowerCase";function C(a){if(a in D)return D[a];return D[a]=navigator.userAgent[B]()[r](a)!=-1}var D={};function E(a,b){var c=function(){};c.prototype=b[w];a.S=b[w];a.prototype=new c}
function F(a,b){var c=Array[w].slice.call(arguments,2)||[];return function(){var e=c.concat(Array[w].slice.call(arguments));return a.apply(b,e)}}function G(a){a=Error(a);a.toString=function(){return this.message};return a}function H(a,b){for(var c=a.split(/\./),e=j,f=0;f<c[v]-1;f++)e[c[f]]||(e[c[f]]={}),e=e[c[f]];e[c[c[v]-1]]=b}function I(a,b,c){a[b]=c}if(!J)var J=H;if(!K)var K=I;google[y].v={};J("google.loader.callbacks",google[y].v);var L={},M={};google[y].eval={};J("google.loader.eval",google[y].eval);
l(google,function(a,b,c){function e(a){var b=a.split(".");if(b[v]>2)throw G("Module: '"+a+"' not found!");else if(typeof b[1]!="undefined")f=b[0],c.packages=c.packages||[],c.packages[m](b[1])}var f=a,c=c||{};if(a instanceof Array||a&&typeof a=="object"&&typeof a[A]=="function"&&typeof a.reverse=="function")for(var i=0;i<a[v];i++)e(a[i]);else e(a);if(a=L[":"+f]){c&&!c.language&&c.locale&&(c.language=c.locale);if(c&&typeof c.callback=="string"&&(i=c.callback,i.match(/^[[\]A-Za-z0-9._]+$/)))i=j.eval(i),
c.callback=i;if((i=c&&c.callback!=g)&&!a.s(b))throw G("Module: '"+f+"' must be loaded before DOM onLoad!");else i?a.m(b,c)?j[x](c.callback,0):a.load(b,c):a.m(b,c)||a.load(b,c)}else throw G("Module: '"+f+"' not found!");});J("google.load",google.load);
google.R=function(a,b){b?(N[v]==0&&(O(j,"load",P),!C("msie")&&!C("safari")&&!C("konqueror")&&C("mozilla")||j.opera?j.addEventListener("DOMContentLoaded",P,!1):C("msie")?k.write("<script defer onreadystatechange='google.loader.domReady()' src=//:><\/script>"):(C("safari")||C("konqueror"))&&j[x](R,10)),N[m](a)):O(j,"load",a)};J("google.setOnLoadCallback",google.R);
function O(a,b,c){if(a.addEventListener)a.addEventListener(b,c,!1);else if(a.attachEvent)a.attachEvent("on"+b,c);else{var e=a["on"+b];a["on"+b]=e!=g?aa([c,e]):c}}function aa(a){return function(){for(var b=0;b<a[v];b++)a[b]()}}var N=[];google[y].N=function(){var a=j.event.srcElement;if(a.readyState=="complete")a.onreadystatechange=g,a.parentNode.removeChild(a),P()};J("google.loader.domReady",google[y].N);var ba={loaded:!0,complete:!0};function R(){ba[k.readyState]?P():N[v]>0&&j[x](R,10)}
function P(){for(var a=0;a<N[v];a++)N[a]();N.length=0}google[y].d=function(a,b,c){if(c){var e;if(a=="script")e=k.createElement("script"),e.type="text/javascript",e.src=b;else if(a=="css")e=k.createElement("link"),e.type="text/css",e.href=b,e.rel="stylesheet";(a=k.getElementsByTagName("head")[0])||(a=k.body.parentNode.appendChild(k.createElement("head")));a.appendChild(e)}else a=="script"?k.write('<script src="'+b+'" type="text/javascript"><\/script>'):a=="css"&&k.write('<link href="'+b+'" type="text/css" rel="stylesheet"></link>')};
J("google.loader.writeLoadTag",google[y].d);google[y].O=function(a){M=a};J("google.loader.rfm",google[y].O);google[y].Q=function(a){for(var b in a)typeof b=="string"&&b&&b[p](0)==":"&&!L[b]&&(L[b]=new S(b[z](1),a[b]))};J("google.loader.rpl",google[y].Q);google[y].P=function(a){if((a=a.specs)&&a[v])for(var b=0;b<a[v];++b){var c=a[b];typeof c=="string"?L[":"+c]=new T(c):(c=new U(c[t],c.baseSpec,c.customSpecs),L[":"+c[t]]=c)}};J("google.loader.rm",google[y].P);google[y].loaded=function(a){L[":"+a.module].l(a)};
J("google.loader.loaded",google[y].loaded);google[y].M=function(){return"qid="+((new Date)[u]().toString(16)+Math.floor(Math.random()*1E7).toString(16))};J("google.loader.createGuidArg_",google[y].M);H("google_exportSymbol",H);H("google_exportProperty",I);google[y].b={};J("google.loader.themes",google[y].b);google[y].b.H="//www.google.com/cse/style/look/bubblegum.css";K(google[y].b,"BUBBLEGUM",google[y].b.H);google[y].b.J="//www.google.com/cse/style/look/greensky.css";K(google[y].b,"GREENSKY",google[y].b.J);
google[y].b.I="//www.google.com/cse/style/look/espresso.css";K(google[y].b,"ESPRESSO",google[y].b.I);google[y].b.L="//www.google.com/cse/style/look/shiny.css";K(google[y].b,"SHINY",google[y].b.L);google[y].b.K="//www.google.com/cse/style/look/minimalist.css";K(google[y].b,"MINIMALIST",google[y].b.K);function T(a){this.a=a;this.o=[];this.n={};this.e={};this.f={};this.j=!0;this.c=-1}
T[w].g=function(a,b){var c="";b!=d&&(b.language!=d&&(c+="&hl="+h(b.language)),b.nocss!=d&&(c+="&output="+h("nocss="+b.nocss)),b.nooldnames!=d&&(c+="&nooldnames="+h(b.nooldnames)),b.packages!=d&&(c+="&packages="+h(b.packages)),b.callback!=g&&(c+="&async=2"),b.style!=d&&(c+="&style="+h(b.style)),b.other_params!=d&&(c+="&"+b.other_params));if(!this.j){google[this.a]&&google[this.a].JSHash&&(c+="&sig="+h(google[this.a].JSHash));var e=[],f;for(f in this.n)f[p](0)==":"&&e[m](f[z](1));for(f in this.e)f[p](0)==
":"&&this.e[f]&&e[m](f[z](1));c+="&have="+h(e[A](","))}return google[y][s]+"/?file="+this.a+"&v="+a+google[y].AdditionalParams+c};T[w].t=function(a){var b=g;a&&(b=a.packages);var c=g;if(b)if(typeof b=="string")c=[a.packages];else if(b[v]){c=[];for(a=0;a<b[v];a++)typeof b[a]=="string"&&c[m](b[a][o](/^\s*|\s*$/,"")[B]())}c||(c=["default"]);b=[];for(a=0;a<c[v];a++)this.n[":"+c[a]]||b[m](c[a]);return b};
l(T[w],function(a,b){var c=this.t(b),e=b&&b.callback!=g;if(e)var f=new V(b.callback);for(var i=[],n=c[v]-1;n>=0;n--){var q=c[n];e&&f.A(q);if(this.e[":"+q])c.splice(n,1),e&&this.f[":"+q][m](f);else i[m](q)}if(c[v]){b&&b.packages&&(b.packages=c.sort()[A](","));for(n=0;n<i[v];n++)q=i[n],this.f[":"+q]=[],e&&this.f[":"+q][m](f);if(!b&&M[":"+this.a]!=g&&M[":"+this.a].versions[":"+a]!=g&&!google[y].AdditionalParams&&this.j){c=M[":"+this.a];google[this.a]=google[this.a]||{};for(var Q in c.properties)Q&&Q[p](0)==
":"&&(google[this.a][Q[z](1)]=c.properties[Q]);google[y].d("script",google[y][s]+c.path+c.js,e);c.css&&google[y].d("css",google[y][s]+c.path+c.css,e)}else(!b||!b.autoloaded)&&google[y].d("script",this.g(a,b),e);if(this.j&&(this.j=!1,this.c=(new Date)[u](),this.c%100!=1))this.c=-1;for(n=0;n<i[v];n++)q=i[n],this.e[":"+q]=!0}});
T[w].l=function(a){if(this.c!=-1)W("al_"+this.a,"jl."+((new Date)[u]()-this.c),!0),this.c=-1;this.o=this.o.concat(a.components);google[y][this.a]||(google[y][this.a]={});google[y][this.a].packages=this.o.slice(0);for(var b=0;b<a.components[v];b++){this.n[":"+a.components[b]]=!0;this.e[":"+a.components[b]]=!1;var c=this.f[":"+a.components[b]];if(c){for(var e=0;e<c[v];e++)c[e].B(a.components[b]);delete this.f[":"+a.components[b]]}}};T[w].m=function(a,b){return this.t(b)[v]==0};T[w].s=function(){return!0};
function V(a){this.D=a;this.q={};this.r=0}V[w].A=function(a){this.r++;this.q[":"+a]=!0};V[w].B=function(a){this.q[":"+a]&&(this.q[":"+a]=!1,this.r--,this.r==0&&j[x](this.D,0))};function U(a,b,c){this.name=a;this.C=b;this.p=c;this.u=this.h=!1;this.k=[];google[y].v[this[t]]=F(this.l,this)}E(U,T);l(U[w],function(a,b){var c=b&&b.callback!=g;c?(this.k[m](b.callback),b.callback="google.loader.callbacks."+this[t]):this.h=!0;(!b||!b.autoloaded)&&google[y].d("script",this.g(a,b),c)});U[w].m=function(a,b){return b&&b.callback!=g?this.u:this.h};U[w].l=function(){this.u=!0;for(var a=0;a<this.k[v];a++)j[x](this.k[a],0);this.k=[]};
var X=function(a,b){return a.string?h(a.string)+"="+h(b):a.regex?b[o](/(^.*$)/,a.regex):""};U[w].g=function(a,b){return this.F(this.w(a),a,b)};
U[w].F=function(a,b,c){var e="";a.key&&(e+="&"+X(a.key,google[y].ApiKey));a.version&&(e+="&"+X(a.version,b));b=google[y].Secure&&a.ssl?a.ssl:a.uri;if(c!=g)for(var f in c)a.params[f]?e+="&"+X(a.params[f],c[f]):f=="other_params"?e+="&"+c[f]:f=="base_domain"&&(b="http://"+c[f]+a.uri[z](a.uri[r]("/",7)));google[this[t]]={};b[r]("?")==-1&&e&&(e="?"+e[z](1));return b+e};U[w].s=function(a){return this.w(a).deferred};U[w].w=function(a){if(this.p)for(var b=0;b<this.p[v];++b){var c=this.p[b];if(RegExp(c.pattern).test(a))return c}return this.C};function S(a,b){this.a=a;this.i=b;this.h=!1}E(S,T);l(S[w],function(a,b){this.h=!0;google[y].d("script",this.g(a,b),!1)});S[w].m=function(){return this.h};S[w].l=function(){};S[w].g=function(a,b){if(!this.i.versions[":"+a]){if(this.i.aliases){var c=this.i.aliases[":"+a];c&&(a=c)}if(!this.i.versions[":"+a])throw G("Module: '"+this.a+"' with version '"+a+"' not found!");}return google[y].GoogleApisBase+"/libs/"+this.a+"/"+a+"/"+this.i.versions[":"+a][b&&b.uncompressed?"uncompressed":"compressed"]};
S[w].s=function(){return!1};var Y=!1,Z=[],ca=(new Date)[u](),W=function(a,b,c){Y||(O(j,"unload",da),Y=!0);if(c){if(!google[y].Secure&&(!google[y].Options||google[y].Options.csi===!1))a=a[B]()[o](/[^a-z0-9_.]+/g,"_"),b=b[B]()[o](/[^a-z0-9_.]+/g,"_"),j[x](F($,g,"//gg.google.com/csi?s=uds&v=2&action="+h(a)+"&it="+h(b)),1E4)}else Z[m]("r"+Z[v]+"="+h(a+(b?"|"+b:""))),j[x](da,Z[v]>5?0:15E3)},da=function(){if(Z[v]){var a=google[y][s];a[r]("http:")==0&&(a=a[o](/^http:/,"https:"));$(a+"/stats?"+Z[A]("&")+"&nc="+(new Date)[u]()+"_"+((new Date)[u]()-
ca));Z.length=0}},$=function(a){var b=new Image,c=$.G++;$.z[c]=b;b.onload=b.onerror=function(){delete $.z[c]};b.src=a;b=g};$.z={};$.G=0;H("google.loader.recordStat",W);H("google.loader.createImageForLogging",$);

}) ();google.loader.rm({"specs":[{"name":"books","baseSpec":{"uri":"http://books.google.com/books/api.js","ssl":null,"key":{"string":"key"},"version":{"string":"v"},"deferred":true,"params":{"callback":{"string":"callback"},"language":{"string":"hl"}}}},"feeds",{"name":"friendconnect","baseSpec":{"uri":"http://www.google.com/friendconnect/script/friendconnect.js","ssl":null,"key":{"string":"key"},"version":{"string":"v"},"deferred":false,"params":{}}},"spreadsheets","identitytoolkit","gdata","visualization",{"name":"sharing","baseSpec":{"uri":"http://www.google.com/s2/sharing/js","ssl":null,"key":{"string":"key"},"version":{"string":"v"},"deferred":false,"params":{"language":{"string":"hl"}}}},"search",{"name":"maps","baseSpec":{"uri":"http://maps.google.com/maps?file\u003dgoogleapi","ssl":"https://maps-api-ssl.google.com/maps?file\u003dgoogleapi","key":{"string":"key"},"version":{"string":"v"},"deferred":true,"params":{"callback":{"regex":"callback\u003d$1\u0026async\u003d2"},"language":{"string":"hl"}}},"customSpecs":[{"uri":"http://maps.google.com/maps/api/js","ssl":"https://maps-api-ssl.google.com/maps/api/js","key":{"string":"key"},"version":{"string":"v"},"deferred":true,"params":{"callback":{"string":"callback"},"language":{"string":"hl"}},"pattern":"^(3|3..*)$"}]},"annotations_v2","wave","orkut",{"name":"annotations","baseSpec":{"uri":"http://www.google.com/reviews/scripts/annotations_bootstrap.js","ssl":null,"key":{"string":"key"},"version":{"string":"v"},"deferred":true,"params":{"callback":{"string":"callback"},"language":{"string":"hl"},"country":{"string":"gl"}}}},"language","earth","ads","elements"]});
google.loader.rfm({":search":{"versions":{":1":"1",":1.0":"1"},"path":"/api/search/1.0/da11a17ee21435ab38fe3d34c57b4e8b/","js":"default+en.I.js","css":"default.css","properties":{":JSHash":"da11a17ee21435ab38fe3d34c57b4e8b",":NoOldNames":false,":Version":"1.0"}},":language":{"versions":{":1":"1",":1.0":"1"},"path":"/api/language/1.0/4c799b5d9590782ad04064fdda233029/","js":"default+en.I.js","properties":{":JSHash":"4c799b5d9590782ad04064fdda233029",":Version":"1.0"}},":feeds":{"versions":{":1":"1",":1.0":"1"},"path":"/api/feeds/1.0/ebcc20169bc505865931499d7e9dca8d/","js":"default+en.I.js","css":"default.css","properties":{":JSHash":"ebcc20169bc505865931499d7e9dca8d",":Version":"1.0"}},":spreadsheets":{"versions":{":0":"1",":0.4":"1"},"path":"/api/spreadsheets/0.4/87ff7219e9f8a8164006cbf28d5e911a/","js":"default.I.js","properties":{":JSHash":"87ff7219e9f8a8164006cbf28d5e911a",":Version":"0.4"}},":wave":{"versions":{":1":"1",":1.0":"1"},"path":"/api/wave/1.0/3b6f7573ff78da6602dda5e09c9025bf/","js":"default.I.js","properties":{":JSHash":"3b6f7573ff78da6602dda5e09c9025bf",":Version":"1.0"}},":annotations":{"versions":{":1":"1",":1.0":"1"},"path":"/api/annotations/1.0/dfca8805c4b6dacbd463750331da710e/","js":"default+en.I.js","properties":{":JSHash":"dfca8805c4b6dacbd463750331da710e",":Version":"1.0"}},":earth":{"versions":{":1":"1",":1.0":"1"},"path":"/api/earth/1.0/a53f4e87830de2a72937039b5507ebdc/","js":"default.I.js","properties":{":JSHash":"a53f4e87830de2a72937039b5507ebdc",":Version":"1.0"}},":picker":{"versions":{":1":"1",":1.0":"1"},"path":"/api/picker/1.0/77d23be1d9a7f6c7632cb056f3de7c8a/","js":"default.I.js","css":"default.css","properties":{":JSHash":"77d23be1d9a7f6c7632cb056f3de7c8a",":Version":"1.0"}}});
google.loader.rpl({":scriptaculous":{"versions":{":1.8.3":{"uncompressed":"scriptaculous.js","compressed":"scriptaculous.js"},":1.8.2":{"uncompressed":"scriptaculous.js","compressed":"scriptaculous.js"},":1.8.1":{"uncompressed":"scriptaculous.js","compressed":"scriptaculous.js"}},"aliases":{":1.8":"1.8.3",":1":"1.8.3"}},":yui":{"versions":{":2.6.0":{"uncompressed":"build/yuiloader/yuiloader.js","compressed":"build/yuiloader/yuiloader-min.js"},":2.9.0":{"uncompressed":"build/yuiloader/yuiloader.js","compressed":"build/yuiloader/yuiloader-min.js"},":2.7.0":{"uncompressed":"build/yuiloader/yuiloader.js","compressed":"build/yuiloader/yuiloader-min.js"},":2.8.0r4":{"uncompressed":"build/yuiloader/yuiloader.js","compressed":"build/yuiloader/yuiloader-min.js"},":2.8.2r1":{"uncompressed":"build/yuiloader/yuiloader.js","compressed":"build/yuiloader/yuiloader-min.js"},":2.8.1":{"uncompressed":"build/yuiloader/yuiloader.js","compressed":"build/yuiloader/yuiloader-min.js"},":3.3.0":{"uncompressed":"build/yui/yui.js","compressed":"build/yui/yui-min.js"}},"aliases":{":3":"3.3.0",":2":"2.9.0",":2.7":"2.7.0",":2.8.2":"2.8.2r1",":2.6":"2.6.0",":2.9":"2.9.0",":2.8":"2.8.2r1",":2.8.0":"2.8.0r4",":3.3":"3.3.0"}},":swfobject":{"versions":{":2.1":{"uncompressed":"swfobject_src.js","compressed":"swfobject.js"},":2.2":{"uncompressed":"swfobject_src.js","compressed":"swfobject.js"}},"aliases":{":2":"2.2"}},":ext-core":{"versions":{":3.1.0":{"uncompressed":"ext-core-debug.js","compressed":"ext-core.js"},":3.0.0":{"uncompressed":"ext-core-debug.js","compressed":"ext-core.js"}},"aliases":{":3":"3.1.0",":3.0":"3.0.0",":3.1":"3.1.0"}},":webfont":{"versions":{":1.0.2":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.1":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.0":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.6":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.19":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.5":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.18":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.17":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.4":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.16":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.3":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.9":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.12":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.13":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.14":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.15":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.10":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"},":1.0.11":{"uncompressed":"webfont_debug.js","compressed":"webfont.js"}},"aliases":{":1":"1.0.19",":1.0":"1.0.19"}},":mootools":{"versions":{":1.2.3":{"uncompressed":"mootools.js","compressed":"mootools-yui-compressed.js"},":1.3.1":{"uncompressed":"mootools.js","compressed":"mootools-yui-compressed.js"},":1.1.1":{"uncompressed":"mootools.js","compressed":"mootools-yui-compressed.js"},":1.2.4":{"uncompressed":"mootools.js","compressed":"mootools-yui-compressed.js"},":1.3.0":{"uncompressed":"mootools.js","compressed":"mootools-yui-compressed.js"},":1.2.1":{"uncompressed":"mootools.js","compressed":"mootools-yui-compressed.js"},":1.2.2":{"uncompressed":"mootools.js","compressed":"mootools-yui-compressed.js"},":1.2.5":{"uncompressed":"mootools.js","compressed":"mootools-yui-compressed.js"},":1.1.2":{"uncompressed":"mootools.js","compressed":"mootools-yui-compressed.js"}},"aliases":{":1":"1.1.2",":1.11":"1.1.1",":1.3":"1.3.1",":1.2":"1.2.5",":1.1":"1.1.2"}},":jqueryui":{"versions":{":1.6.0":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.8.0":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.8.2":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.8.1":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.8.9":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.8.7":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.8.8":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.8.12":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.8.5":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.8.11":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.7.2":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.8.6":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.8.10":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.7.3":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.7.0":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.7.1":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.8.4":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.5.3":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"},":1.5.2":{"uncompressed":"jquery-ui.js","compressed":"jquery-ui.min.js"}},"aliases":{":1.8":"1.8.12",":1.7":"1.7.3",":1.6":"1.6.0",":1":"1.8.12",":1.5":"1.5.3",":1.8.3":"1.8.4"}},":chrome-frame":{"versions":{":1.0.2":{"uncompressed":"CFInstall.js","compressed":"CFInstall.min.js"},":1.0.1":{"uncompressed":"CFInstall.js","compressed":"CFInstall.min.js"},":1.0.0":{"uncompressed":"CFInstall.js","compressed":"CFInstall.min.js"}},"aliases":{":1":"1.0.2",":1.0":"1.0.2"}},":prototype":{"versions":{":1.7.0.0":{"uncompressed":"prototype.js","compressed":"prototype.js"},":1.6.0.2":{"uncompressed":"prototype.js","compressed":"prototype.js"},":1.6.1.0":{"uncompressed":"prototype.js","compressed":"prototype.js"},":1.6.0.3":{"uncompressed":"prototype.js","compressed":"prototype.js"}},"aliases":{":1.7":"1.7.0.0",":1.6.1":"1.6.1.0",":1":"1.7.0.0",":1.6":"1.6.1.0",":1.7.0":"1.7.0.0",":1.6.0":"1.6.0.3"}},":jquery":{"versions":{":1.3.1":{"uncompressed":"jquery.js","compressed":"jquery.min.js"},":1.3.0":{"uncompressed":"jquery.js","compressed":"jquery.min.js"},":1.3.2":{"uncompressed":"jquery.js","compressed":"jquery.min.js"},":1.2.3":{"uncompressed":"jquery.js","compressed":"jquery.min.js"},":1.2.6":{"uncompressed":"jquery.js","compressed":"jquery.min.js"},":1.4.3":{"uncompressed":"jquery.js","compressed":"jquery.min.js"},":1.4.4":{"uncompressed":"jquery.js","compressed":"jquery.min.js"},":1.5.1":{"uncompressed":"jquery.js","compressed":"jquery.min.js"},":1.5.0":{"uncompressed":"jquery.js","compressed":"jquery.min.js"},":1.4.0":{"uncompressed":"jquery.js","compressed":"jquery.min.js"},":1.5.2":{"uncompressed":"jquery.js","compressed":"jquery.min.js"},":1.4.1":{"uncompressed":"jquery.js","compressed":"jquery.min.js"},":1.4.2":{"uncompressed":"jquery.js","compressed":"jquery.min.js"}},"aliases":{":1":"1.5.2",":1.5":"1.5.2",":1.4":"1.4.4",":1.3":"1.3.2",":1.2":"1.2.6"}},":dojo":{"versions":{":1.2.3":{"uncompressed":"dojo/dojo.xd.js.uncompressed.js","compressed":"dojo/dojo.xd.js"},":1.3.1":{"uncompressed":"dojo/dojo.xd.js.uncompressed.js","compressed":"dojo/dojo.xd.js"},":1.1.1":{"uncompressed":"dojo/dojo.xd.js.uncompressed.js","compressed":"dojo/dojo.xd.js"},":1.3.0":{"uncompressed":"dojo/dojo.xd.js.uncompressed.js","compressed":"dojo/dojo.xd.js"},":1.3.2":{"uncompressed":"dojo/dojo.xd.js.uncompressed.js","compressed":"dojo/dojo.xd.js"},":1.6.0":{"uncompressed":"dojo/dojo.xd.js.uncompressed.js","compressed":"dojo/dojo.xd.js"},":1.4.3":{"uncompressed":"dojo/dojo.xd.js.uncompressed.js","compressed":"dojo/dojo.xd.js"},":1.5.1":{"uncompressed":"dojo/dojo.xd.js.uncompressed.js","compressed":"dojo/dojo.xd.js"},":1.5.0":{"uncompressed":"dojo/dojo.xd.js.uncompressed.js","compressed":"dojo/dojo.xd.js"},":1.2.0":{"uncompressed":"dojo/dojo.xd.js.uncompressed.js","compressed":"dojo/dojo.xd.js"},":1.4.0":{"uncompressed":"dojo/dojo.xd.js.uncompressed.js","compressed":"dojo/dojo.xd.js"},":1.4.1":{"uncompressed":"dojo/dojo.xd.js.uncompressed.js","compressed":"dojo/dojo.xd.js"}},"aliases":{":1":"1.6.0",":1.6":"1.6.0",":1.5":"1.5.1",":1.4":"1.4.3",":1.3":"1.3.2",":1.2":"1.2.3",":1.1":"1.1.1"}}});
}

(function() {
function aa(a){throw a;}var b=true,c=null,g=false,ba=encodeURIComponent,ca=parseInt,i=String,da=window,k=Number,ea=Function,m=Object,fa=document,ha=decodeURIComponent,ia=Math;function ja(a,d){return a.statusText=d}function ka(a,d){return a.toString=d}function la(a,d){return a.length=d}function ma(a,d){return a.width=d}function na(a,d){return a.content=d}function oa(a,d){return a.responseText=d}function pa(a,d){return a.scheme=d}function n(a,d){return a.value=d}
function qa(a,d){return a.currentTarget=d}function ra(a,d){return a.target=d}function sa(a,d){return a.status=d}function ta(a,d){return a.remove=d}function ua(a,d){return a.keyCode=d}function va(a,d){return a.href=d}function o(a,d){return a.type=d}function wa(a,d){return a.name=d}function xa(a,d){return a.label=d}function ya(a,d){return a.height=d}
var za="appendChild",q="push",Aa="toString",Ba="hash",r="length",Ca="propertyIsEnumerable",Da="title",Ea="version",t="prototype",Fa="test",Ga="lang",Ha="exec",Ia="width",Ja="replace",Ka="document",La="load",Ma="split",Na="floor",Oa="content",Pa="responseText",Qa="scheme",u="constructor",w="value",Ra="location",y="indexOf",Sa="hasOwnProperty",Ta="dispatchEvent",Ua="style",Va="nodeName",Xa="body",Ya="write",Za="target",z="call",$a="status",ab="remove",bb="port",cb="createElement",db="protocol",eb="keyCode",
fb="forEach",gb="setAttribute",A="href",hb="substring",ib="handleEvent",jb="every",B="type",kb="contains",lb="apply",mb="headers",nb="childNodes",ob="bind",pb="attributes",qb="name",rb="parentNode",sb="fileName",tb="label",ub="height",vb="splice",wb="getTime",xb="join",yb="toLowerCase",zb=zb||{},Ab=this,Bb=function(a,d,e){var h=a[Ma]("."),j=e||Ab;!(h[0]in j)&&j.execScript&&j.execScript("var "+h[0]);for(var l;h[r]&&(l=h.shift());)if(!h[r]&&C(d))j[l]=d;else j=j[l]?j[l]:(j[l]={})},Cb=function(a,d){for(var e=
a[Ma]("."),h=d||Ab,j;j=e.shift();)if(h[j])h=h[j];else return c;return h},Db=function(a){var d=typeof a;if(d=="object")if(a){if(a instanceof Array||!(a instanceof m)&&m[t][Aa][z](a)=="[object Array]"||typeof a[r]=="number"&&typeof a[vb]!="undefined"&&typeof a[Ca]!="undefined"&&!a[Ca]("splice"))return"array";if(!(a instanceof m)&&(m[t][Aa][z](a)=="[object Function]"||typeof a[z]!="undefined"&&typeof a[Ca]!="undefined"&&!a[Ca]("call")))return"function"}else return"null";else if(d=="function"&&typeof a[z]==
"undefined")return"object";return d},C=function(a){return a!==undefined},Eb=function(a){return Db(a)=="array"},Fb=function(a){var d=Db(a);return d=="array"||d=="object"&&typeof a[r]=="number"},Gb=function(a){return typeof a=="string"},Hb=function(a){return Db(a)=="function"},Ib=function(a){var d=Db(a);return d=="object"||d=="array"||d=="function"},Lb=function(a){if(a[Sa]&&a[Sa](Jb))return a[Jb];a[Jb]||(a[Jb]=++Kb);return a[Jb]},Jb="closure_hashCode_"+ia[Na](ia.random()*2147483648)[Aa](36),Kb=0,Mb=
function(a,d){var e=a.Kt;if(arguments[r]>2){var h=Array[t].slice[z](arguments,2);e&&h.unshift[lb](h,e);e=h}d=a.Mt||d;a=a.Lt||a;var j,l=d||Ab;j=e?function(){var p=Array[t].slice[z](arguments);p.unshift[lb](p,e);return a[lb](l,p)}:function(){return a[lb](l,arguments)};j.Kt=e;j.Mt=d;j.Lt=a;return j},Nb=Date.now||function(){return(new Date)[wb]()},D=function(a,d,e){Bb(a,d,e)},Ob=function(a,d){function e(){}e.prototype=d[t];a.js=d[t];a.prototype=new e;a[t].constructor=a};
ea[t].bind=function(a){if(arguments[r]>1){var d=Array[t].slice[z](arguments,1);d.unshift(this,a);return Mb[lb](c,d)}else return Mb(this,a)};ea[t].e=function(a){Ob(this,a)};var Pb=function(a,d){var e=a[r]-d[r];return e>=0&&a.lastIndexOf(d,e)==e},Qb=function(a){return/^[\s\xa0]*$/[Fa](a)},Rb=function(a){return a[Ja](/^[\s\xa0]+|[\s\xa0]+$/g,"")},Sb=/^[a-zA-Z0-9\-_.!~*'()]*$/,Tb=function(a){a=i(a);if(!Sb[Fa](a))return ba(a);return a},Ub=function(a){return ha(a[Ja](/\+/g," "))},$b=function(a,d){if(d)return a[Ja](Vb,"&amp;")[Ja](Wb,"&lt;")[Ja](Xb,"&gt;")[Ja](Yb,"&quot;");else{if(!Zb[Fa](a))return a;if(a[y]("&")!=-1)a=a[Ja](Vb,"&amp;");if(a[y]("<")!=-1)a=a[Ja](Wb,"&lt;");
if(a[y](">")!=-1)a=a[Ja](Xb,"&gt;");if(a[y]('"')!=-1)a=a[Ja](Yb,"&quot;");return a}},Vb=/&/g,Wb=/</g,Xb=/>/g,Yb=/\"/g,Zb=/[&<>\"]/,ac=function(a,d){return a[y](d)!=-1},bc=function(a,d){return(new Array(d+1))[xb](a)},cc=function(a,d,e){var h=C(e)?a.toFixed(e):i(a),j=h[y](".");if(j==-1)j=h[r];return bc("0",ia.max(0,d-j))+h},ec=function(a,d){for(var e=0,h=Rb(i(a))[Ma]("."),j=Rb(i(d))[Ma]("."),l=ia.max(h[r],j[r]),p=0;e==0&&p<l;p++){var s=h[p]||"",v=j[p]||"",F=new RegExp("(\\d*)(\\D*)","g"),x=new RegExp("(\\d*)(\\D*)",
"g");do{var S=F[Ha](s)||["","",""],M=x[Ha](v)||["","",""];if(S[0][r]==0&&M[0][r]==0)break;var N=S[1][r]==0?0:ca(S[1],10),ga=M[1][r]==0?0:ca(M[1],10);e=dc(N,ga)||dc(S[2][r]==0,M[2][r]==0)||dc(S[2],M[2])}while(e==0)}return e},dc=function(a,d){if(a<d)return-1;else if(a>d)return 1;return 0};Nb();var fc=function(a,d,e){if(a[y])return a[y](d,e);if(Array[y])return Array[y](a,d,e);for(var h=e==c?0:e<0?ia.max(0,a[r]+e):e,j=h;j<a[r];j++)if(j in a&&a[j]===d)return j;return-1},gc=function(a,d,e){if(a[fb])a[fb](d,e);else if(Array[fb])Array[fb](a,d,e);else for(var h=a[r],j=Gb(a)?a[Ma](""):a,l=0;l<h;l++)l in j&&d[z](e,j[l],l,a)},hc=function(a,d,e){if(a[jb])return a[jb](d,e);if(Array[jb])return Array[jb](a,d,e);for(var h=a[r],j=Gb(a)?a[Ma](""):a,l=0;l<h;l++)if(l in j&&!d[z](e,j[l],l,a))return g;return b},
ic=function(a,d,e){for(var h=a[r],j=Gb(a)?a[Ma](""):a,l=0;l<h;l++)if(l in j&&d[z](e,j[l],l,a))return l;return-1},jc=function(a,d){if(a[kb])return a[kb](d);return fc(a,d)>-1},kc=function(a){if(!Eb(a))for(var d=a[r]-1;d>=0;d--)delete a[d];la(a,0)},lc=function(a,d){var e=fc(a,d),h;if(h=e!=-1)Array[t][vb][z](a,e,1)[r]==1;return h},mc=function(a,d,e){var h=ic(a,d,e);if(h>=0){Array[t][vb][z](a,h,1)[r]==1;return b}return g},nc=function(a){if(Eb(a))return a.concat();else{for(var d=[],e=0,h=a[r];e<h;e++)d[e]=
a[e];return d}},oc=function(a){if(Eb(a))return a.concat();return nc(a)},pc=function(a){for(var d=1;d<arguments[r];d++){var e=arguments[d];if(Fb(e)){e=oc(e);a[q][lb](a,e)}else a[q](e)}};if("StopIteration"in Ab)var qc=Ab.StopIteration;else qc=Error("StopIteration");var rc=function(){};rc[t].qd=function(){aa(qc)};rc[t].__iterator__=function(){return this};var sc=function(a,d,e){for(var h in a)d[z](e,a[h],h,a)},tc=function(a){var d=0;for(var e in a)d++;return d},uc=function(a){var d=[],e=0;for(var h in a)d[e++]=a[h];return d},vc=function(a){var d=[],e=0;for(var h in a)d[e++]=h;return d},wc=function(a,d){for(var e in a)if(a[e]==d)return b;return g},xc=function(a){var d={};for(var e in a)d[e]=a[e];return d},yc=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],zc=function(a){for(var d,e,h=1;h<
arguments[r];h++){e=arguments[h];for(d in e)a[d]=e[d];for(var j=0;j<yc[r];j++){d=yc[j];if(m[t][Sa][z](e,d))a[d]=e[d]}}};var Ac=function(a){if(typeof a.ta=="function")return a.ta();if(Fb(a)||Gb(a))return a[r];return tc(a)},Bc=function(a){if(typeof a.Ca=="function")return a.Ca();if(Gb(a))return a[Ma]("");if(Fb(a)){for(var d=[],e=a[r],h=0;h<e;h++)d[q](a[h]);return d}return uc(a)},Cc=function(a){if(typeof a.hb=="function")return a.hb();if(typeof a.Ca=="function")return undefined;if(Fb(a)||Gb(a)){for(var d=[],e=a[r],h=0;h<e;h++)d[q](h);return d}return vc(a)},Dc=function(a,d){if(typeof a[kb]=="function")return a[kb](d);
if(typeof a.pg=="function")return a.pg(d);if(Fb(a)||Gb(a))return jc(a,d);return wc(a,d)},Ec=function(a,d,e){if(typeof a[fb]=="function")a[fb](d,e);else if(Fb(a)||Gb(a))gc(a,d,e);else for(var h=Cc(a),j=Bc(a),l=j[r],p=0;p<l;p++)d[z](e,j[p],h&&h[p],a)},Fc=function(a,d,e){if(typeof a[jb]=="function")return a[jb](d,e);if(Fb(a)||Gb(a))return hc(a,d,e);for(var h=Cc(a),j=Bc(a),l=j[r],p=0;p<l;p++)if(!d[z](e,j[p],h&&h[p],a))return g;return b};var Gc=function(a){this.Aa={};this.Da=[];var d=arguments[r];if(d>1){if(d%2)aa(Error("Uneven number of arguments"));for(var e=0;e<d;e+=2)this.Va(arguments[e],arguments[e+1])}else a&&this.og(a)};Gc[t].L=0;Gc[t].hg=0;Gc[t].ta=function(){return this.L};Gc[t].Ca=function(){this.Tf();for(var a=[],d=0;d<this.Da[r];d++){var e=this.Da[d];a[q](this.Aa[e])}return a};Gc[t].hb=function(){this.Tf();return this.Da.concat()};Gc[t].xb=function(a){return Hc(this.Aa,a)};
Gc[t].pg=function(a){for(var d=0;d<this.Da[r];d++){var e=this.Da[d];if(Hc(this.Aa,e)&&this.Aa[e]==a)return b}return g};Gc[t].ie=function(a,d){if(this===a)return b;if(this.L!=a.ta())return g;var e=d||Ic;this.Tf();for(var h,j=0;h=this.Da[j];j++)if(!e(this.ra(h),a.ra(h)))return g;return b};var Ic=function(a,d){return a===d};Gc[t].clear=function(){this.Aa={};la(this.Da,0);this.hg=this.L=0};ta(Gc[t],function(a){if(Hc(this.Aa,a)){delete this.Aa[a];this.L--;this.hg++;this.Da[r]>2*this.L&&this.Tf();return b}return g});
Gc[t].Tf=function(){if(this.L!=this.Da[r]){for(var a=0,d=0;a<this.Da[r];){var e=this.Da[a];if(Hc(this.Aa,e))this.Da[d++]=e;a++}la(this.Da,d)}if(this.L!=this.Da[r]){var h={};for(d=a=0;a<this.Da[r];){e=this.Da[a];if(!Hc(h,e)){this.Da[d++]=e;h[e]=1}a++}la(this.Da,d)}};Gc[t].ra=function(a,d){if(Hc(this.Aa,a))return this.Aa[a];return d};Gc[t].Va=function(a,d){if(!Hc(this.Aa,a)){this.L++;this.Da[q](a);this.hg++}this.Aa[a]=d};
Gc[t].og=function(a){var d,e;if(a instanceof Gc){d=a.hb();e=a.Ca()}else{d=vc(a);e=uc(a)}for(var h=0;h<d[r];h++)this.Va(d[h],e[h])};Gc[t].Sa=function(){return new Gc(this)};Gc[t].__iterator__=function(a){this.Tf();var d=0,e=this.Da,h=this.Aa,j=this.hg,l=this,p=new rc;p.qd=function(){for(;1;){if(j!=l.hg)aa(Error("The map has changed since the iterator was created"));if(d>=e[r])aa(qc);var s=e[d++];return a?s:h[s]}};return p};var Hc=function(a,d){return m[t][Sa][z](a,d)};var Jc=function(a){this.Aa=new Gc;a&&this.og(a)},Kc=function(a){var d=typeof a;return d=="object"&&a?"o"+Lb(a):d.substr(0,1)+a};Jc[t].ta=function(){return this.Aa.ta()};Jc[t].add=function(a){this.Aa.Va(Kc(a),a)};Jc[t].og=function(a){for(var d=Bc(a),e=d[r],h=0;h<e;h++)this.add(d[h])};Jc[t].yf=function(a){for(var d=Bc(a),e=d[r],h=0;h<e;h++)this[ab](d[h])};ta(Jc[t],function(a){return this.Aa[ab](Kc(a))});Jc[t].clear=function(){this.Aa.clear()};Jc[t].contains=function(a){return this.Aa.xb(Kc(a))};
Jc[t].Ca=function(){return this.Aa.Ca()};Jc[t].Sa=function(){return new Jc(this)};Jc[t].ie=function(a){return this.ta()==Ac(a)&&this.jt(a)};Jc[t].jt=function(a){var d=Ac(a);if(this.ta()>d)return g;if(!(a instanceof Jc)&&d>5)a=new Jc(a);return Fc(this,function(e){return Dc(a,e)})};Jc[t].__iterator__=function(){return this.Aa.__iterator__(g)};var Nc=function(a,d){try{var e=Lc(a),h="Message: "+$b(e.message)+'\nUrl: <a href="view-source:'+e[sb]+'" target="_new">'+e[sb]+"</a>\nLine: "+e.lineNumber+"\n\nBrowser stack:\n"+$b(e.stack+"-> ")+"[end]\n\nJS stack traversal:\n"+$b(Mc(d)+"-> ");return h}catch(j){return"Exception trying to expose exception! You win, we lose. "+j}},Lc=function(a){var d=Cb("window.location.href");return typeof a=="string"?{message:a,name:"Unknown error",lineNumber:"Not available",fileName:d,stack:"Not available"}:!a.lineNumber||
!a[sb]||!a.stack?{message:a.message,name:a[qb],lineNumber:a.lineNumber||a.line||"Not available",fileName:a[sb]||a.filename||a.sourceURL||d,stack:a.stack||"Not available"}:a},Mc=function(a){return Oc(a||arguments.callee.caller,[])},Oc=function(a,d){var e=[];if(jc(d,a))e[q]("[...circular reference...]");else if(a&&d[r]<50){e[q](Pc(a)+"(");for(var h=a.arguments,j=0;j<h[r];j++){j>0&&e[q](", ");var l,p=h[j];switch(typeof p){case "object":l=p?"object":"null";break;case "string":l=p;break;case "number":l=
i(p);break;case "boolean":l=p?"true":"false";break;case "function":l=(l=Pc(p))?l:"[fn]";break;case "undefined":default:l=typeof p;break}if(l[r]>40)l=l.substr(0,40)+"...";e[q](l)}d[q](a);e[q](")\n");try{e[q](Oc(a.caller,d))}catch(s){e[q]("[exception trying to get caller]\n")}}else a?e[q]("[...long stack...]"):e[q]("[end]");return e[xb]("")},Pc=function(a){var d=i(a);if(!Qc[d]){var e=/function ([^\(]+)/[Ha](d);if(e){var h=e[1];Qc[d]=h}else Qc[d]="[Anonymous]"}return Qc[d]},Qc={};var Sc=function(a,d,e,h,j){this.bu=typeof j=="number"?j:Rc++;this.cu=h||Nb();this.pd=a;this.au=d;this.Zt=e};Sc[t].Ns=c;Sc[t].Ms=c;var Rc=0;Sc[t].Ct=function(a){this.Ns=a};Sc[t].Dt=function(a){this.Ms=a};Sc[t].uh=function(){return this.pd};Sc[t].Si=function(a){this.pd=a};var Tc=function(a){this.qt=a;this.Fh=c;this.Pt={};this.ct=[]};Tc[t].pd=c;var Uc=function(a,d){wa(this,a);n(this,d)};ka(Uc[t],function(){return this[qb]});new Uc("OFF",Infinity);new Uc("SHOUT",1200);new Uc("SEVERE",1000);new Uc("WARNING",900);new Uc("INFO",800);var Vc=new Uc("CONFIG",700),Wc=new Uc("FINE",500);new Uc("FINER",400);new Uc("FINEST",300);new Uc("ALL",0);Tc[t].u=function(){return this.qt};Tc[t].Zs=function(){return this.Fh};Tc[t].Si=function(a){this.pd=a};Tc[t].uh=function(){return this.pd};
Tc[t].Dh=function(a){if(this.pd)return a[w]>=this.pd[w];if(this.Fh)return this.Fh.Dh(a);return g};Tc[t].log=function(a,d,e){this.Dh(a)&&this.kt(this.Ws(a,d,e))};Tc[t].Ws=function(a,d,e){var h=new Sc(a,i(d),this.qt);if(e){h.Ct(e);h.Dt(Nc(e,arguments.callee.caller))}return h};Tc[t].kt=function(a){if(this.Dh(a.uh()))for(var d=this;d;){d.Bs(a);d=d.Zs()}};Tc[t].Bs=function(a){for(var d=0;d<this.ct[r];d++)this.ct[d](a)};Tc[t].Et=function(a){this.Fh=a};Tc[t].zs=function(a,d){this.Pt[a]=d};
var Xc={},Yc=c,Zc=function(){if(!Yc){Yc=new Tc("");Xc[""]=Yc;Yc.Si(Vc)}},ad=function(a){Zc();return a in Xc?Xc[a]:$c(a)},$c=function(a){var d=new Tc(a),e=a[Ma]("."),h=e[e[r]-1];la(e,e[r]-1);var j=e[xb]("."),l=ad(j);l.zs(h,d);d.Et(l);return Xc[a]=d};var bd=function(a,d){this.x=C(a)?a:0;this.y=C(d)?d:0};bd[t].Sa=function(){return new bd(this.x,this.y)};ka(bd[t],function(){return"("+this.x+", "+this.y+")"});var cd=function(a,d){ma(this,a);ya(this,d)};cd[t].Sa=function(){return new cd(this[Ia],this[ub])};ka(cd[t],function(){return"("+this[Ia]+" x "+this[ub]+")"});cd[t].ceil=function(){ma(this,ia.ceil(this[Ia]));ya(this,ia.ceil(this[ub]));return this};cd[t].floor=function(){ma(this,ia[Na](this[Ia]));ya(this,ia[Na](this[ub]));return this};cd[t].round=function(){ma(this,ia.round(this[Ia]));ya(this,ia.round(this[ub]));return this};cd[t].scale=function(a){this.width*=a;this.height*=a;return this};var dd,ed,fd,gd,hd,id,jd,kd,ld,md,nd=function(){return Ab.navigator?Ab.navigator.userAgent:c},od=function(){return Ab.navigator},pd=function(){id=hd=gd=fd=ed=dd=g;var a;if(a=nd()){var d=od();dd=a[y]("Opera")==0;ed=!dd&&a[y]("MSIE")!=-1;gd=(fd=!dd&&a[y]("WebKit")!=-1)&&a[y]("Mobile")!=-1;id=(hd=!dd&&!fd&&d.product=="Gecko")&&d.vendor=="Camino"}};pd();
var qd=dd,rd=ed,sd=hd,td=fd,ud=function(){var a=od();return a&&a.platform||""},vd=ud(),wd=function(){jd=ac(vd,"Mac");kd=ac(vd,"Win");ld=ac(vd,"Linux");md=!!od()&&ac(od().appVersion||"","X11")};wd();var xd=function(){var a="",d;if(qd&&Ab.opera){var e=Ab.opera[Ea];a=typeof e=="function"?e():e}else{if(sd)d=/rv\:([^\);]+)(\)|;)/;else if(rd)d=/MSIE\s+([^\);]+)(\)|;)/;else if(td)d=/WebKit\/(\S+)/;if(d){var h=d[Ha](nd());a=h?h[1]:""}}return a},yd=xd();var Ad=function(a,d){sc(d,function(e,h){if(h=="style")a[Ua].cssText=e;else if(h=="class")a.className=e;else if(h=="for")a.htmlFor=e;else if(h in zd)a[gb](zd[h],e);else a[h]=e})},zd={cellpadding:"cellPadding",cellspacing:"cellSpacing",colspan:"colSpan",rowspan:"rowSpan",valign:"vAlign",height:"height",width:"width",usemap:"useMap",frameborder:"frameBorder",type:"type"},Bd=function(a,d){a[za](d)},Cd=function(a){return a&&a[rb]?a[rb].removeChild(a):c},Dd=function(a,d){var e=d[rb];e&&e.replaceChild(a,
d)},Ed=td&&ec(yd,"521")<=0,Fd=function(a,d){if(typeof a[kb]!="undefined"&&!Ed&&d.nodeType==1)return a==d||a[kb](d);if(typeof a.compareDocumentPosition!="undefined")return a==d||Boolean(a.compareDocumentPosition(d)&16);for(;d&&a!=d;)d=d[rb];return d==a},Gd=function(a){var d;return d=td?a[Ka]||a.contentWindow[Ka]:a.contentDocument||a.contentWindow[Ka]},Hd=function(a){this.Ls=a||Ab[Ka]||fa};Hd[t].Mb=Ad;Hd[t].createElement=function(a){return this.Ls[cb](a)};Hd[t].createTextNode=function(a){return this.Ls.createTextNode(a)};
Hd[t].appendChild=Bd;Hd[t].removeNode=Cd;Hd[t].replaceNode=Dd;Hd[t].contains=Fd;var Id=function(){};Id[t].um=g;Id[t].rg=function(){if(!this.um){this.um=b;this.gb()}};Id[t].gb=function(){};var Jd=function(a,d){Id[z](this);this.pt=d;this.je=[];this.Is(a)};Ob(Jd,Id);Jd[t].qh=c;Jd[t].sh=c;Jd[t].eg=function(a){this.qh=a};Jd[t].mr=function(a){this.sh=a};Jd[t].mc=function(){if(this.je[r])return this.je.pop();return this.pm()};Jd[t].xf=function(a){this.je[r]<this.pt?this.je[q](a):this.tm(a)};Jd[t].Is=function(a){if(a>this.pt)aa(Error("[goog.structs.SimplePool] Initial cannot be greater than max"));for(var d=0;d<a;d++)this.je[q](this.pm())};Jd[t].pm=function(){return this.qh?this.qh():{}};
Jd[t].tm=function(a){if(this.sh)this.sh(a);else if(Hb(a.rg))a.rg();else for(var d in a)delete a[d]};Jd[t].gb=function(){Jd.js.gb[z](this);for(var a=this.je;a[r];)this.tm(a.pop());delete this.je};var Kd=function(a,d){o(this,a);ra(this,d);qa(this,this[Za])};Ob(Kd,Id);Kd[t].gb=function(){delete this[B];delete this[Za];delete this.currentTarget};Kd[t].tc=g;Kd[t].Af=b;Kd[t].stopPropagation=function(){this.tc=b};Kd[t].preventDefault=function(){this.Af=g};var Ld=function(a,d){a&&this.qc(a,d)};Ob(Ld,Kd);o(Ld[t],c);ra(Ld[t],c);Ld[t].relatedTarget=c;Ld[t].offsetX=0;Ld[t].offsetY=0;Ld[t].clientX=0;Ld[t].clientY=0;Ld[t].screenX=0;Ld[t].screenY=0;Ld[t].button=0;ua(Ld[t],0);Ld[t].charCode=0;Ld[t].ctrlKey=g;Ld[t].altKey=g;Ld[t].shiftKey=g;Ld[t].metaKey=g;Ld[t].Sb=c;
Ld[t].qc=function(a,d){o(this,a[B]);ra(this,a[Za]||a.srcElement);qa(this,d);this.relatedTarget=a.relatedTarget?a.relatedTarget:this[B]=="mouseover"?a.fromElement:this[B]=="mouseout"?a.toElement:c;this.offsetX=typeof a.layerX=="number"?a.layerX:a.offsetX;this.offsetY=typeof a.layerY=="number"?a.layerY:a.offsetY;this.clientX=typeof a.clientX=="number"?a.clientX:a.pageX;this.clientY=typeof a.clientY=="number"?a.clientY:a.pageY;this.screenX=a.screenX||0;this.screenY=a.screenY||0;this.button=a.button;
ua(this,a[eb]||0);this.charCode=a.charCode||(this[B]=="keypress"?a[eb]:0);this.ctrlKey=a.ctrlKey;this.altKey=a.altKey;this.shiftKey=a.shiftKey;this.metaKey=a.metaKey;this.Sb=a;delete this.Af;delete this.tc};Ld[t].stopPropagation=function(){this.tc=b;if(this.Sb.stopPropagation)this.Sb.stopPropagation();else this.Sb.cancelBubble=b};Ld[t].preventDefault=function(){this.Af=g;if(this.Sb.preventDefault)this.Sb.preventDefault();else{this.Sb.returnValue=g;try{ua(this.Sb,-1)}catch(a){}}};
Ld[t].gb=function(){Ld.js.gb[z](this);this.Sb=c};var Md=function(){},Nd=0;Md[t].Ch=c;Md[t].wf=c;Md[t].ar=c;Md[t].src=c;o(Md[t],c);Md[t].Sf=c;Md[t].Bg=c;Md[t].Tb=0;Md[t].zf=g;Md[t].jm=g;Md[t].qc=function(a,d,e,h,j,l){if(Hb(a))this.Ch=b;else if(a&&a[ib]&&Hb(a[ib]))this.Ch=g;else aa(Error("Invalid listener argument"));this.wf=a;this.ar=d;this.src=e;o(this,h);this.Sf=!!j;this.Bg=l;this.jm=g;this.Tb=++Nd;this.zf=g};Md[t].handleEvent=function(a){if(this.Ch)return this.wf[z](this.Bg||this.src,a);return this.wf[ib][z](this.wf,a)};var Od={},Pd={},Qd={},Rd=new Jd(0,600);Rd.eg(function(){return{L:0,Jb:0}});Rd.mr(function(a){a.L=0});var Sd=new Jd(0,600);Sd.eg(function(){return[]});Sd.mr(function(a){la(a,0);delete a.Cg;delete a.Xq});var Td=new Jd(0,600);Td.eg(function(){var a=function(d){return Ud[z](a.src,a.Tb,d)};return a});var Vd=function(){return new Md},Wd=new Jd(0,600);Wd.eg(Vd);
var Xd=function(){return new Ld},Yd=function(){var a=c;if(rd){a=new Jd(0,600);a.eg(Xd)}return a},Zd=Yd(),$d="on",be={},ce=function(a,d,e,h,j){if(d)if(Eb(d)){for(var l=0;l<d[r];l++)ce(a,d[l],e,h,j);return c}else{var p=!!h,s=Pd;d in s||(s[d]=Rd.mc());s=s[d];if(!(p in s)){s[p]=Rd.mc();s.L++}s=s[p];var v=Lb(a),F,x;s.Jb++;if(s[v]){F=s[v];for(l=0;l<F[r];l++){x=F[l];if(x.wf==e&&x.Bg==j){if(x.zf)break;return F[l].Tb}}}else{F=s[v]=Sd.mc();s.L++}var S=Td.mc();S.src=a;x=Wd.mc();x.qc(e,S,a,d,p,j);var M=x.Tb;
S.Tb=M;F[q](x);Od[M]=x;Qd[v]||(Qd[v]=Sd.mc());Qd[v][q](x);if(a.addEventListener){if(a==Ab||!a.qm)a.addEventListener(d,S,p)}else a.attachEvent(de(d),S);return M}else aa(Error("Invalid event type"))},ee=function(a,d,e,h,j){if(Eb(d)){for(var l=0;l<d[r];l++)ee(a,d[l],e,h,j);return c}var p=!!h,s=fe(a,d,p);if(!s)return g;for(l=0;l<s[r];l++)if(s[l].wf==e&&s[l].Sf==p&&s[l].Bg==j)return ge(s[l].Tb);return g},ge=function(a){if(!Od[a])return g;var d=Od[a];if(d.zf)return g;var e=d.src,h=d[B],j=d.ar,l=d.Sf;if(e.removeEventListener){if(e==
Ab||!e.qm)e.removeEventListener(h,j,l)}else e.detachEvent&&e.detachEvent(de(h),j);var p=Lb(e),s=Pd[h][l][p];if(Qd[p]){var v=Qd[p];lc(v,d);v[r]==0&&delete Qd[p]}d.zf=b;s.Xq=b;he(h,l,p,s);delete Od[a];return b},he=function(a,d,e,h){if(!h.Cg)if(h.Xq){for(var j=0,l=0;j<h[r];j++)if(h[j].zf)Wd.xf(h[j]);else{if(j!=l)h[l]=h[j];l++}la(h,l);h.Xq=g;if(l==0){Sd.xf(h);delete Pd[a][d][e];Pd[a][d].L--;if(Pd[a][d].L==0){Rd.xf(Pd[a][d]);delete Pd[a][d];Pd[a].L--}if(Pd[a].L==0){Rd.xf(Pd[a]);delete Pd[a]}}}},ie=function(a,
d,e){var h=0,j=a==c,l=d==c,p=e==c;e=!!e;if(j)sc(Qd,function(S){for(var M=S[r]-1;M>=0;M--){var N=S[M];if((l||d==N[B])&&(p||e==N.Sf)){ge(N.Tb);h++}}});else{var s=Lb(a);if(Qd[s])for(var v=Qd[s],F=v[r]-1;F>=0;F--){var x=v[F];if((l||d==x[B])&&(p||e==x.Sf)){ge(x.Tb);h++}}}return h},fe=function(a,d,e){var h=Pd;if(d in h){h=h[d];if(e in h){h=h[e];var j=Lb(a);if(h[j])return h[j]}}return c},de=function(a){if(a in be)return be[a];return be[a]=$d+a},ke=function(a,d,e,h,j){var l=1,p=Lb(d);if(a[p]){a.Jb--;var s=
a[p];if(s.Cg)s.Cg++;else s.Cg=1;try{for(var v=s[r],F=0;F<v;F++){var x=s[F];if(x&&!x.zf)l&=je(x,j)!==g}}finally{s.Cg--;he(e,h,p,s)}}return Boolean(l)},je=function(a,d){var e=a[ib](d);a.jm&&ge(a.Tb);return e},le=function(a,d){if(Gb(d))d=new Kd(d,a);else if(d instanceof Kd)ra(d,d[Za]||a);else{var e=d;d=new Kd(d[B],a);zc(d,e)}var h=1,j,l=d[B],p=Pd;if(!(l in p))return b;p=p[l];var s=b in p,v;if(s){j=[];for(var F=a;F;F=F.mp())j[q](F);v=p[b];v.Jb=v.L;for(var x=j[r]-1;!d.tc&&x>=0&&v.Jb;x--){qa(d,j[x]);h&=
ke(v,j[x],d[B],b,d)&&d.Af!=g}}var S=g in p;if(S){v=p[g];v.Jb=v.L;if(s)for(x=0;!d.tc&&x<j[r]&&v.Jb;x++){qa(d,j[x]);h&=ke(v,j[x],d[B],g,d)&&d.Af!=g}else for(var M=a;!d.tc&&M&&v.Jb;M=M.mp()){qa(d,M);h&=ke(v,M,d[B],g,d)&&d.Af!=g}}return Boolean(h)},Ud=function(a,d){if(!Od[a])return b;var e=Od[a],h=e[B],j=Pd;if(!(h in j))return b;j=j[h];var l,p;if(rd){var s=d||Cb("window.event"),v=b in j,F=g in j;if(v){if(s[eb]<0||s.returnValue!=undefined)return b;me(s)}var x=Zd.mc();x.qc(s,this);l=b;try{if(v){for(var S=
Sd.mc(),M=x.currentTarget;M;M=M[rb])S[q](M);p=j[b];p.Jb=p.L;for(var N=S[r]-1;!x.tc&&N>=0&&p.Jb;N--){qa(x,S[N]);l&=ke(p,S[N],h,b,x)}if(F){p=j[g];p.Jb=p.L;for(N=0;!x.tc&&N<S[r]&&p.Jb;N++){qa(x,S[N]);l&=ke(p,S[N],h,g,x)}}}else l=je(e,x)}finally{if(S){la(S,0);Sd.xf(S)}x.rg();Zd.xf(x)}return l}var ga=new Ld(d,this);try{l=je(e,ga)}finally{ga.rg()}return l},me=function(a){var d=g;if(a[eb]==0)try{ua(a,-1);return}catch(e){d=b}if(d||a.returnValue==undefined)a.returnValue=b};var ne=function(){};Ob(ne,Id);ne[t].qm=b;ne[t].$q=c;ne[t].mp=function(){return this.$q};ne[t].addEventListener=function(a,d,e,h){ce(this,a,d,e,h)};ne[t].removeEventListener=function(a,d,e,h){ee(this,a,d,e,h)};ne[t].dispatchEvent=function(a){return le(this,a)};ne[t].gb=function(){ne.js.gb[z](this);ie(this);this.$q=c};var oe=function(a){if(/^\s*$/[Fa](a))return g;var d=/\\["\\\/bfnrtu]/g,e=/"[^"\\\n\r\u2028\u2029\x00-\x1f\x80-\x9f]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,h=/(?:^|:|,)(?:[\s\u2028\u2029]*\[)+/g,j=/^[\],:{}\s\u2028\u2029]*$/;return j[Fa](a[Ja](d,"@")[Ja](e,"]")[Ja](h,""))},pe=function(a){var d=i(a);if(oe(d))try{return eval("("+d+")")}catch(e){}aa(Error("Invalid JSON string: "+d))},qe=function(a){return eval("("+a+")")};/\uffff/[Fa]("\uffff");var re=/^(?:([^:\/?#]+):)?(?:\/\/(?:([^\/?#]*)@)?([^\/?#:@]*)(?::([0-9]+))?)?([^?#]+)?(?:\?([^#]*))?(?:#(.*))?$/,se=function(a){return a.match(re)};var te=function(a,d){var e;if(a instanceof te){this.wd(d==c?a.Vs():d);this.na(a.ya());this.ak(a.bt());this.hi(a.Ts());this.kj(a.rp());this.gj(a.Me());this.vj(a.Kp().Sa());this.wi(a.Us())}else if(a&&(e=se(i(a)))){this.wd(!!d);this.na(e[1]||"",b);this.ak(e[2]||"",b);this.hi(e[3]||"",b);this.kj(e[4]);this.gj(e[5]||"",b);this.Ft(e[6]||"",b);this.wi(e[7]||"",b)}else{this.wd(!!d);this.pb=new ue(c,this,this.Ib)}};te[t].uc="";te[t].gg="";te[t].Vf="";te[t].dg=c;te[t].bg="";te[t].Wf="";te[t].Vq=g;
te[t].Ib=g;ka(te[t],function(){if(this.wb)return this.wb;var a=[];this.uc&&a[q](ve(this.uc,we),":");if(this.Vf){a[q]("//");this.gg&&a[q](ve(this.gg,we),"@");a[q](xe(this.Vf));this.dg!=c&&a[q](":",i(this.rp()))}this.bg&&a[q](ve(this.bg,ye));var d=i(this.pb);d&&a[q]("?",d);this.Wf&&a[q]("#",ve(this.Wf,ze));return this.wb=a[xb]("")});te[t].Sa=function(){return Ae(this.uc,this.gg,this.Vf,this.dg,this.bg,this.pb.Sa(),this.Wf,this.Ib)};te[t].ya=function(){return this.uc};
te[t].na=function(a,d){this.Rb();delete this.wb;if(this.uc=d?a?ha(a):"":a)this.uc=this.uc[Ja](/:$/,"");return this};te[t].bt=function(){return this.gg};te[t].ak=function(a,d){this.Rb();delete this.wb;this.gg=d?a?ha(a):"":a;return this};te[t].Ts=function(){return this.Vf};te[t].hi=function(a,d){this.Rb();delete this.wb;this.Vf=d?a?ha(a):"":a;return this};te[t].rp=function(){return this.dg};
te[t].kj=function(a){this.Rb();delete this.wb;if(a){a=k(a);if(isNaN(a)||a<0)aa(Error("Bad port number "+a));this.dg=a}else this.dg=c;return this};te[t].Me=function(){return this.bg};te[t].gj=function(a,d){this.Rb();delete this.wb;this.bg=d?a?ha(a):"":a;return this};te[t].vj=function(a,d){this.Rb();delete this.wb;if(a instanceof ue){this.pb=a;this.pb.ls=this;this.pb.wd(this.Ib)}else{d||(a=ve(a,Be));this.pb=new ue(a,this,this.Ib)}return this};te[t].Ft=function(a,d){return this.vj(a,d)};te[t].Kp=function(){return this.pb};
te[t].rb=function(a,d){this.Rb();delete this.wb;this.pb.Va(a,d);return this};te[t].yh=function(a){return this.pb.ra(a)};te[t].Us=function(){return this.Wf};te[t].wi=function(a,d){this.Rb();delete this.wb;this.Wf=d?a?ha(a):"":a;return this};te[t].removeParameter=function(a){this.Rb();this.pb[ab](a);return this};te[t].Nb=function(a){this.Vq=a};te[t].Rb=function(){if(this.Vq)aa(Error("Tried to modify a read-only Uri"))};te[t].wd=function(a){this.Ib=a;this.pb&&this.pb.wd(a)};te[t].Vs=function(){return this.Ib};
var Ae=function(a,d,e,h,j,l,p,s){var v=new te(c,s);a&&v.na(a);d&&v.ak(d);e&&v.hi(e);h&&v.kj(h);j&&v.gj(j);l&&v.vj(l);p&&v.wi(p);return v},xe=function(a){if(Gb(a))return ba(a);return c},Ce=/^[a-zA-Z0-9\-_.!~*'():\/;?]*$/,ve=function(a,d){var e=c;if(Gb(a)){e=a;Ce[Fa](e)||(e=encodeURI(a));if(e.search(d)>=0)e=e[Ja](d,De)}return e},De=function(a){var d=a.charCodeAt(0);return"%"+(d>>4&15)[Aa](16)+(d&15)[Aa](16)},we=/[#\/\?@]/g,ye=/[\#\?]/g,Be=/[\#\?@]/g,ze=/#/g,Ee=function(a,d){var e=se(a),h=se(d);return e[3]==
h[3]&&e[4]==h[4]},ue=function(a,d,e){this.hc=a||c;this.ls=d||c;this.Ib=!!e};ue[t].yb=function(){if(!this.ba){this.ba=new Gc;if(this.hc)for(var a=this.hc[Ma]("&"),d=0;d<a[r];d++){var e=a[d][y]("="),h=c,j=c;if(e>=0){h=a[d][hb](0,e);j=a[d][hb](e+1)}else h=a[d];h=Ub(h);h=this.lc(h);this.add(h,j?Ub(j):"")}}};ue[t].ba=c;ue[t].L=c;ue[t].ta=function(){this.yb();return this.L};
ue[t].add=function(a,d){this.yb();this.vf();a=this.lc(a);if(this.xb(a)){var e=this.ba.ra(a);Eb(e)?e[q](d):this.ba.Va(a,[e,d])}else this.ba.Va(a,d);this.L++;return this};ta(ue[t],function(a){this.yb();a=this.lc(a);if(this.ba.xb(a)){this.vf();var d=this.ba.ra(a);if(Eb(d))this.L-=d[r];else this.L--;return this.ba[ab](a)}return g});ue[t].clear=function(){this.vf();this.ba&&this.ba.clear();this.L=0};ue[t].xb=function(a){this.yb();a=this.lc(a);return this.ba.xb(a)};
ue[t].pg=function(a){var d=this.Ca();return jc(d,a)};ue[t].hb=function(){this.yb();for(var a=this.ba.Ca(),d=this.ba.hb(),e=[],h=0;h<d[r];h++){var j=a[h];if(Eb(j))for(var l=0;l<j[r];l++)e[q](d[h]);else e[q](d[h])}return e};ue[t].Ca=function(a){this.yb();var d;if(a){var e=this.lc(a);if(this.xb(e)){var h=this.ba.ra(e);if(Eb(h))return h;else{d=[];d[q](h)}}else d=[]}else{var j=this.ba.Ca();d=[];for(var l=0;l<j[r];l++){var p=j[l];Eb(p)?pc(d,p):d[q](p)}}return d};
ue[t].Va=function(a,d){this.yb();this.vf();a=this.lc(a);if(this.xb(a)){var e=this.ba.ra(a);if(Eb(e))this.L-=e[r];else this.L--}this.ba.Va(a,d);this.L++;return this};ue[t].ra=function(a,d){this.yb();a=this.lc(a);if(this.xb(a)){var e=this.ba.ra(a);return Eb(e)?e[0]:e}else return d};ue[t].fg=function(a,d){this.yb();this.vf();a=this.lc(a);if(this.xb(a)){var e=this.ba.ra(a);if(Eb(e))this.L-=e[r];else this.L--}if(d[r]>0){this.ba.Va(a,d);this.L+=d[r]}};
ka(ue[t],function(){if(this.hc)return this.hc;if(!this.ba)return"";for(var a=[],d=0,e=this.ba.hb(),h=0;h<e[r];h++){var j=e[h],l=Tb(j),p=this.ba.ra(j);if(Eb(p))for(var s=0;s<p[r];s++){d>0&&a[q]("&");a[q](l,"=",Tb(p[s]));d++}else{d>0&&a[q]("&");a[q](l,"=",Tb(p));d++}}return this.hc=a[xb]("")});ue[t].vf=function(){delete this.rm;delete this.hc;this.ls&&delete this.ls.wb};ue[t].Sa=function(){var a=new ue;if(this.rm)a.rm=this.rm;if(this.hc)a.hc=this.hc;if(this.ba)a.ba=this.ba.Sa();return a};
ue[t].lc=function(a){var d=i(a);if(this.Ib)d=d[yb]();return d};ue[t].wd=function(a){var d=a&&!this.Ib;if(d){this.yb();this.vf();Ec(this.ba,function(e,h){var j=h[yb]();if(h!=j){this[ab](h);this.add(j,e)}},this)}this.Ib=a};ue[t].extend=function(){for(var a=0;a<arguments[r];a++){var d=arguments[a];Ec(d,function(e,h){this.add(h,e)},this)}};var Fe=function(){ne[z](this)},Ge,He;Ob(Fe,ne);var Ie=b;if(da[Ra]&&(da[Ra][Ba][y]("xdrp")==1||da[Ra].search[y]("xdrp")==1))if(rd)fa.execCommand("Stop");else if(sd)da.stop();else aa(Error("stopped"));
var Je=function(a,d,e,h,j){var l=new Fe;d&&ce(l,"complete",d);ce(l,"ready",l.reset);l.ib(a,e,h,j)},Ke=function(a){He=a},Le=ad("goog.net.CrossDomainRpc"),Me=function(a,d){return'<textarea name="'+a+'">'+(d&&(Gb(d)||d[u]==i)?d[Ja](/&/g,"&amp;"):d)+"</textarea>"},Ne=function(){if(Ge)return Ge;if(sd)for(var a=fa.getElementsByTagName("link"),d=0;d<a[r];d++){var e=a[d];if(e.rel=="stylesheet"&&Ee(e[A],da[Ra][A])&&e[A][y]("?")<0)return e[A][Ma]("#")[0]}var h=fa.getElementsByTagName("img");for(d=0;d<h[r];d++){var j=
h[d];if(Ee(j.src,da[Ra][A])&&j.src[y]("?")<0)return j.src[Ma]("#")[0]}if(!Ie)aa(Error("No suitable dummy resource specified or detected for this page"));if(rd)return da[Ra][A][Ma]("#")[0];else{var l=da[Ra][A],p=l[y]("/",l[y]("//")+2),s=l[hb](0,p);return s+"/robots.txt"}},Oe=0;
Fe[t].ib=function(a,d,e,h){var j=this.Dg=fa[cb]("iframe"),l=Oe++;j.id="xdrq-"+l;if(!He){j[Ua].position="absolute";j[Ua].top="-5000px";j[Ua].left="-5000px"}fa[Xa][za](j);var p=[];p[q](Me("xdpe:request-id",l));var s=Ne();Le.log(Wc,"dummyUri: "+s);p[q](Me("xdpe:dummy-uri",s));if(e)for(var v in e){var F=e[v];p[q](Me("xdp:"+v,F))}if(h)for(v in h){F=h[v];p[q](Me("xdh:"+v,F))}var x='<body><form method="'+(d=="GET"?"GET":"POST")+'" action="'+a+'">'+p[xb]("")+"</form></body>",S=Gd(j);S.open();S[Ya](x);S.close();
S.forms[0].submit();S=c;this.St=ce(j,"load",function(){Le.log(Wc,"response ready");this.Wt=b},g,this);this.vt()};Fe[t].vt=function(){this.Gt=0;var a=da.setInterval(Mb(function(){this.Js(a)},this),50)};
Fe[t].Js=function(a){var d=this.Dg.contentWindow,e=d.frames[r],h=c;if(e>0&&Pe(h=d.frames[e-1])){Le.log(Wc,"xd response ready");var j=Qe(h)[hb](1),l=new ue(j),p=[],s=k(l.ra("n"));Le.log(Wc,"xd response number of chunks: "+s);for(var v=0;v<s;v++){var F=d.frames[v];if(!F||!F[Ra]||!F[Ra][A]){Le.log(Wc,"xd response iframe not ready");return}var x=Qe(F),S=x[y]("chunk")+"chunk"[r]+1,M=x[hb](S);p[q](M)}da.clearInterval(a);var N=p[xb]("");rd||(N=ha(N));sa(this,k(l.ra("status")));oa(this,N);this.xt=l.ra("isDataJson")==
"true";this.responseHeaders=qe(l.ra("headers"));this[Ta]("ready");this[Ta]("complete")}else if(this.Wt){this.Gt+=50;if(this.Gt>500){Le.log(Wc,"xd response timed out");da.clearInterval(a);sa(this,500);oa(this,"response timed out");this[Ta]("ready");this[Ta]("error");this[Ta]("complete")}}};var Pe=function(a){try{return Qe(a)[y]("xdrp-info")==1}catch(d){return g}},Qe=function(a){var d=a[Ra][A],e=d[y]("?"),h=d[y]("#"),j=e<0?h:h<0?e:ia.min(e,h);return d[hb](j)};
Fe[t].getResponseJson=function(){return this.xt?qe(this[Pa]):undefined};Fe[t].reset=function(){if(!He){Le.log(Wc,"request frame removed: "+this.Dg.id);ge(this.St);this.Dg[rb].removeChild(this.Dg)}delete this.Dg};var Re=function(a){var d=a[y]("?");if(d>0)a=a[hb](0,d);var e=a[y]("#");if(e>0)a=a[hb](0,e);return a};Fe[t].getResponseHeader=function(a){return Ib(this.responseHeaders)?this.responseHeaders[a]:undefined};Re(fa.referrer);var Se=/\s*;\s*/,Te=function(a,d,e,h,j){if(/[;=]/[Fa](a))aa(Error('Invalid cookie name "'+a+'"'));if(/;/[Fa](d))aa(Error('Invalid cookie value "'+d+'"'));C(e)||(e=-1);var l=j?";domain="+j:"",p=h?";path="+h:"",s;if(e<0)s="";else if(e==0){var v=new Date(1970,1,1);s=";expires="+v.toUTCString()}else{var F=new Date((new Date)[wb]()+e*1000);s=";expires="+F.toUTCString()}fa.cookie=a+"="+d+l+p+s},Ue=function(a,d){for(var e=a+"=",h=i(fa.cookie)[Ma](Se),j=0,l;l=h[j];j++)if(l[y](e)==0)return l.substr(e[r]);
return d},Ve=function(a,d,e){var h=C(Ue(a));Te(a,"",0,d,e);return h};var We=function(){this.os="g314-"};We[t].xh=function(a){return this.os+a};We[t].Va=function(a,d,e,h,j){Te(this.xh(a),d,e,h,j)};We[t].ra=function(a,d){return Ue(this.xh(a),d)};ta(We[t],function(a,d,e){return Ve(this.xh(a),d,e)});We[t].yf=function(){for(var a=this.hb(),d=a[r]-1;d>=0;d--)this[ab](a[d])};We[t].Do=function(){for(var a=i(fa.cookie)[Ma](Se),d=[],e=[],h,j,l,p=0;l=a[p];p++){h=l[y](this.os);j=l[y]("=");if(h==0&&j>-1){d[q](l[hb](5,j));e[q](l[hb](j+1))}}return{keys:d,values:e}};We[t].hb=function(){return this.Do().keys};
We[t].Ca=function(){return this.Do().values};var Xe=function(){this.TOKEN_DELIMITER="#2";this.URL_PREFIX="https://www.google.com/accounts/";this.AUTH_SUB_REQUEST_JS="AuthSubRequestJS";this.AUTH_SUB_SESSION_TOKEN_JS="AuthSubSessionTokenJS";this.AUTH_SUB_TOKEN_INFO_JS="AuthSubTokenInfoJS";this.AUTH_SUB_REVOKE_TOKEN_JS="AuthSubRevokeTokenJS"};var Ye=function(a){a||(a=new Xe);this.ob=a};Ye[t].Ys=function(a,d,e){var h=new te(this.ob.URL_PREFIX+this.ob.AUTH_SUB_REQUEST_JS);h.rb("session","1");h.rb("scope",a);h.rb("next",d);e&&h.rb("hd",e);return h[Aa]()};Ye[t].wt=function(a,d){if(Qb(a==c?"":i(a)))aa(Error("Invalid scope."));var e=fa[Ra][A],h=e[y]("#");if(h>=0)e=e[hb](0,h);va(top[Ra],this.Ys(a,e,d))};Ye[t].Os=function(a,d,e){Je(this.ob.URL_PREFIX+this.ob.AUTH_SUB_SESSION_TOKEN_JS,Mb(this.Ps,this,a,e),"POST",{auth:d})};
Ye[t].Ps=function(a,d,e){if(!e||!e[Za]||!e[Za][Pa]||!e[Za].xt)aa(Error("Could not sign in, invalid response from server.  Please try again."));var h=qe(e[Za][Pa]);if(!h.auth)aa(Error("Could not sign in, invalid response from server. Please try again."));d(a,h.auth);var j=fa[Ra][A],l=j[y](this.ob.TOKEN_DELIMITER);if(l>=0)j=j[hb](0,l);this.zt(j)};Ye[t].ht=function(a){var d=/#.+$/,e=top[Ra][A][Ja](d,""),h=a[Ja](d,"");return e==h};
Ye[t].zt=function(a){if(td&&this.ht(a)){va(top[Ra],a);var d=fa[cb]("input");o(d,"button");n(d,"reload");d.onclick=function(){da[Ra].reload()};d[Ua].display="none";fa[Xa][za](d);var e=fa.createEvent("MouseEvents");e.initMouseEvent("click",b,b,fa.defaultView,1,0,0,0,0,g,g,g,g,0,c);var h=function(){d[Ta](e)};da.setTimeout(h,1000)}else va(top[Ra],a)};Ye[t].yg=function(a,d){Je(this.ob.URL_PREFIX+this.ob.AUTH_SUB_TOKEN_INFO_JS,d,"POST",{auth:a.$f()})};
Ye[t].yt=function(a,d){Je(this.ob.URL_PREFIX+this.ob.AUTH_SUB_REVOKE_TOKEN_JS,d,"POST",{auth:a.$f()})};var Ze=function(a,d){this.At=a;this.Ub=d||""};Ze[t].Eb=function(){return this.At};Ze[t].$f=function(){return this.Ub};Ze[t].contains=function(a){if(!a)return g;for(var d=this.At[Ma](" "),e=0;e<d[r];e++)if(a[y](d[e])>-1)return b;return g};var $e=function(a){this.ns="scope-";this.ts="scope";this.vs="token";this.rs="pending";this.rd=[];this.cg=c;a||(a=new We);this.Uf=a};$e[t].add=function(a){this.rd[q](a)};ta($e[t],function(a){var d=function(e){return e.Eb()==a};mc(this.rd,d)});$e[t].yf=function(){kc(this.rd);this.cg=c};$e[t].Yf=function(a){for(var d=0;d<this.rd[r];d++){var e=this.rd[d];if(e[kb](a))return e}return c};$e[t].md=function(){return this.rd};$e[t].Pr=function(a){this.cg=a};$e[t].$s=function(){return this.cg};
$e[t].br=function(){this.cg=c};$e[t].Wq=function(a){if(a)return this.Yf(a)!=c;return this.md()[r]>0};$e[t].write=function(){this.Uf.yf();for(var a=0;a<this.rd[r];a++){var d=this.rd[a],e=this.ns+a,h=new ue;h.add(this.ts,d.Eb());h.add(this.vs,d.$f());this.Uf.Va(e,h[Aa]())}this.cg!=c&&this.Uf.Va(this.rs,this.cg.Eb())};
$e[t].load=function(){this.yf();this.br();for(var a=this.Uf.hb(),d=0;d<a[r];d++){var e=a[d];if(e==this.rs)this.Pr(new Ze(this.Uf.ra(e)));else if(e[y](this.ns)==0){var h=new ue(this.Uf.ra(e)),j=h.ra(this.ts),l=h.ra(this.vs);C(j)&&!(j===c)&&this.add(new Ze(j,l))}}};var af={LOGGED_OUT:0,LOGGING_IN:1,LOGGED_IN:2};D("google.accounts.AuthSubStatus",af);D("google.accounts.AuthSubStatus.LOGGED_OUT",0);D("google.accounts.AuthSubStatus.LOGGING_IN",1);D("google.accounts.AuthSubStatus.LOGGED_IN",2);var bf=function(a){a||(a=new Xe);this.ob=a;this.qa=new $e;this.lh=new Ye(a);this.rh=c};bf[t].mh=function(a){this.qa[La]();this.rh=a;var d=this.qa.Yf(a);if(d)return d.$f();return""};bf[t].lt=function(a,d){a=a||this.rh;this.qa[La]();var e=this.qa.Yf(a);if(e!=c)return e.$f();this.qa.Pr(new Ze(a));this.qa[Ya]();this.lh.wt(a,d);return c};
bf[t].ut=function(){var a=fa[Ra][A];if(!(a[y](this.ob.TOKEN_DELIMITER)<0)){var d=Ub(fa[Ra][Ba][hb](1));this.qa[La]();var e=this.qa.$s().Eb();this.lh.Os(e,d,function(h){return function(j,l){h[La]();h.br();h.add(new Ze(j,l));h[Ya]()}}(this.qa))}};bf[t].ot=function(a,d){var e=[];if(d=d||this.rh){d=this.qa.Yf(d);d!=c&&e[q](d)}else{this.qa[La]();e=this.qa.md()}if(e[r]==0){a();return g}this.er(e,a);return b};
bf[t].er=function(a,d){if(a[r]==0)d&&d();else{var e=a.pop();this.qa[La]();this.qa[ab](e.Eb());this.qa[Ya]();this.lh.yt(e,Mb(this.er,this,a,d))}};bf[t].yg=function(a,d){this.qa[La]();var e=d||this.rh,h=c;if(e)h=this.qa.Yf(e);else{var j=this.qa.md();h=j[r]>0&&j[0]}if(!h)return g;this.lh.yg(h,a);return b};bf[t].Zf=function(a){if(fa[Ra][A][y](this.ob.TOKEN_DELIMITER)>0)return 1;this.qa[La]();if(a){if(this.qa.Wq(a))return 2}else if(this.qa.Wq())return 2;return 0};
bf[t].md=function(){var a=[];this.qa[La]();for(var d=this.qa.md(),e=0;e<d[r];e++)a[q](d[e].Eb());return a};var cf=new bf,df=function(){cf.ut()};ce(da,"load",df);D("google.accounts.user",cf);D("google.accounts.user.checkLogin",cf.mh);D("google.accounts.user.getInfo",cf.yg);D("google.accounts.user.getScopes",cf.md);D("google.accounts.user.getStatus",cf.Zf);D("google.accounts.user.login",cf.lt);D("google.accounts.user.logout",cf.ot);if(typeof framework=="undefined")framework=undefined;if(typeof gadgets=="undefined")gadgets=undefined;if(typeof XULDocument=="undefined")XULDocument=undefined;var ef=framework?c:this,E={};D("google.gdata",E);E.runtime={};
E.runtime.detect=function(){var a=E.runtime;if(typeof framework=="object"&&framework.graphics){o(a,a.TYPE.GD);a.isIe=b}else if(typeof ef.gadgets=="object"&&ef.gadgets.io){o(a,a.TYPE.OS);a.detectBrowser()}else if(typeof ef._IG_Prefs=="function"){o(a,a.TYPE.IG);a.detectBrowser()}else if(typeof ef.widget=="function"&&ef.widget.identifier&&typeof ef.widget.openApplication=="function"){o(a,a.TYPE.MD);a.isSafari=b;a.isKhtml=b}else if(typeof ef.GM_xmlhttpRequest=="function"){o(a,a.TYPE.GM);a.isGecko=b}else if(typeof ef.konfabulatorVersion==
"function")o(a,a.TYPE.KF);else if(typeof ef.XULDocument=="object"&&ef[Ka]instanceof ef.XULDocument){o(a,a.TYPE.FE);a.isGecko=b}else{o(a,a.TYPE.UP);a.detectBrowser()}};E.runtime.detectBrowser=function(){var a=navigator.userAgent,d=E.runtime;d.isOpera=typeof opera!="undefined";d.isIe=!d.isOpera&&a[y]("MSIE")!=-1;d.isSafari=!d.isOpera&&a[y]("Safari")!=-1;d.isGecko=!d.isOpera&&navigator.product=="Gecko"&&!d.isSafari;d.isKonqueror=!d.isOpera&&a[y]("Konqueror")!=-1;d.isKhtml=d.isKonqueror||d.isSafari};
E.runtime.TYPE={FE:"Firefox Extension",GM:"GreaseMonkey",GD:"Google Desktop",IG:"Google Personalized Start Page",KF:"Yahoo Widget Engine",MD:"Mac OS X Dashboard",OS:"OpenSocial Gadget",UP:"Unprivileged"};E.runtime.detect();E.util={};E.util.BUG_MSG='Please rerun the "genesis javascript" command and rebuild your JavaScript library. If this error persists, please report this (probable) BUG to xapi-client@google.com (see Firebug console or some text on this page in IE): ';E.util.trim=function(a){return Gb(a)?Rb(a):a};E.util.it=function(a){return Gb(a)||a&&a[u]==i};
E.util.convertXmlTextToDom=function(a){if(E.runtime[B]==E.runtime.TYPE.GD){var d=new DOMDocument;d.loadXML(a);return d}else if(E.runtime.isIe){d=new ActiveXObject("Microsoft.XMLDOM");d.async=g;d.loadXML(a);return d}else if(typeof ef.DOMParser!="undefined"){var e=new DOMParser;return e.parseFromString(a,"text/xml")}else aa(Error("runtime not supported"))};E.util.convertXmlTextToJavaScript=function(a){a=E.util.trim(a);if(a[r]==0)return c;var d=E.util.convertXmlTextToDom(a);return E.util.convertDomToJavaScript(d)};
E.util.convertDomToJavaScript=function(a){if(E.runtime.isIe){for(var d=a.lastChild,e=E.util.oh(d),h={},j=a.firstChild[pb],l=0;l<j[r];l++){var p=j[l];h[p[Va]]=p.nodeValue}h[d[Va]]=e;return h}else{d=a.documentElement;e=E.util.oh(d);h={version:a.xmlVersion||"1.0",encoding:a.xmlEncoding||"UTF-8"};h[e.channel?"rss":d[Va]]=e;E.util.buildNamespaceDictionaries(e);return h}};
E.util.oh=function(a){var d={};if(a[pb])for(var e=0;e<a[pb][r];e++){var h=a[pb][e],j=h[Va][Ja](/:/g,"$"),l=h.nodeValue;if(j[y]("_moz-")<0)d[j]=l}if(a[nb][r]==1&&a[nb][0].nodeType==3)d.$t=a[nb][0].nodeValue;else for(e=0;e<a[nb][r];e++){var p=a[nb][e];if(p.nodeType!=3){j=p.tagName;j=j[Ja](/:/g,"$");var s=d[j];if(s){if(Db(s)!="array")d[j]=[d[j]];d[j][q](E.util.oh(p))}else{var v=E.util.oh(p);d[j]=j=="entry"?[v]:v}}}return d};
E.util.convertJsonTextToJavaScript=function(a){a=E.util.trim(a);if(a[r]==0)return c;var d=a[Ja](/\r/g,"\\r"),e=d[Ja](/\n/g,"\\n"),h=eval("("+e+")");E.util.buildNamespaceDictionaries(h.feed||h.entry);return h};E.util.convertEntryToAtom=function(a,d){var e="<?xml version='"+(a.$version||"1.0")+"' encoding='"+(a.$encoding||"UTF-8")+"' ?>";return e+E.util.convertJavaScriptToAtom("entry",a,d)};E.util.ft=function(a){return Pb(a,"___")};
E.util.lm=function(a,d,e,h){var j=d.$t;e[q]("<",a);for(var l in d)if(l.charAt(0)!="$"&&l!="__proto__"&&!E.util.ft(l)){var p=d[l],s=typeof p;if(s=="string"||s=="number"||s=="boolean"){l=l[Ja]("$",":");e[q](" ",l,"='",E.util.Qt(p),"'")}else if(p&&s=="object")j=b}if(j){e[q](">");for(l in d)if(l.charAt(0)!="$"&&l!="__proto__"&&!E.util.ft(l))if((p=d[l])&&typeof p=="object"){l=l[Ja]("$",":");if(Db(p)=="array")for(var v=0,F=p[r];v<F;v++)E.util.lm(l,p[v],e,h);else l=="content"&&h?h(l,p,e):E.util.lm(l,p,e,
h)}d.$t&&e[q](E.util.escapeXmlContent(d.$t));e[q]("</",a,">")}else e[q]("/>")};E.util.convertJavaScriptToAtom=function(a,d,e){var h=[];E.util.lm(a,d,h,e);return h[xb]("")};(function(){for(var a="",d=0;d<32;d++)if(d!=9&&d!=10&&d!=13){var e=(d<16?"0":"")+d[Aa](16);a+="\\x"+e}E.util.Ut=new RegExp("["+a+"]","g")})();E.util.Vt=function(a){return a[Ja](E.util.Ut,"")};E.util.escapeXmlContent=function(a){return a&&E.util.it(a)?E.util.Vt(a)[Ja](/&/g,"&amp;")[Ja](/</g,"&lt;")[Ja](/>/g,"&gt;"):a};
E.util.Qt=function(a){return a&&E.util.it(a)?E.util.escapeXmlContent(a)[Ja](/"/g,"&quot;")[Ja](/'/g,"&apos;"):a};E.util.buildNamespaceDictionaries=function(a){for(var d in a){var e=a[d];if(d[y]("xmlns")==0){var h=d=="xmlns"?"":d[hb]("xmlns$"[r]);a.$ns||(a.$ns={});a.$ns[h]=e;a.$rns||(a.$rns={});a.$rns[e]=h}}};E.util.kb=function(a,d){var e=a.link;if(e)for(var h=0;h<e[r];h++){var j=e[h];if(j.rel==d)return j}return c};E.util.copy=function(a){var d={};for(var e in a)d[e]=a[e];return d};
E.util.log=function(a){if(ef.console&&typeof ef.console.log=="function")ef.console.log(a);else{var d=fa[cb]("div");d.innerHTML=a;fa[Xa][za](d)}};E.util.isService=function(a,d){return a[y]("google.com/"+d+"/")>0};E.util.getRandomInt=function(a,d){return ia[Na](ia.random()*(d-a+1)+a)};E.util.mutateTo=function(a,d){if(!a)return undefined;if(a.__proto__){a.__proto__=d[t];a.constructor=d;d[z](a);return a}else{var e=new d;for(var h in a)e[h]=a[h];e.__proto__=d[t];e.constructor=d;d[z](e);return e}};
E.util.handleError=function(a,d){if(!d||!(d instanceof ea))aa(a);return d[z](this,a)};E.util.getTimezoneOffsetString=function(a){var d,e=a.getTimezoneOffset();if(e==0)d="Z";else{var h=ia.abs(e)/60,j=ia[Na](h),l=(h-j)*60;d=(e>0?"-":"+")+cc(j,2)+":"+cc(l,2)}return d};E.util.vh=function(a,d,e){for(var h=0;h<a[r];h++){var j=a[h];if((!d||d==j.q())&&(!e||e==j.o()))return h}return undefined};E.util.It=/("[^"]*":")(.*?)(","[^"]*":)/;
E.util.Rt=function(a){a=a[Ja](/\}/g,',"_\u0001":null}');for(var d=0;;){var e=a[hb](d),h=E.util.It[Ha](e);if(!h)break;var j=0;if(h[2][y]('"')>=0){var l=h[2][Ja](/"/g,'\\"'),p=h.index+h[1][r],s=h[2][r];j=p+s;a=a[hb](0,d+p)+l+a[hb](d+j)}d+=j+2}return a=a[Ja](/,"_\x01":null\}/g,"}")};var ff=function(a,d){this.date=a;this.dateOnly=d==b};D("google.gdata.DateTime",ff);ff[t].getDate=function(){return this.date};D("google.gdata.DateTime.prototype.getDate",ff[t].getDate);ff[t].setDate=function(a){this.date=a};D("google.gdata.DateTime.prototype.setDate",ff[t].setDate);ff[t].Bh=function(){return this.dateOnly};D("google.gdata.DateTime.prototype.isDateOnly",ff[t].Bh);ff[t].kr=function(a){this.dateOnly=a};D("google.gdata.DateTime.prototype.setDateOnly",ff[t].kr);
ff[t].ie=function(a){return this.dateOnly==a.dateOnly&&this.date[wb]()==a.date[wb]()};D("google.gdata.DateTime.prototype.equals",ff[t].ie);
var G=function(a){var d=ca(a[hb](0,4),10),e=ca(a[hb](5,7),10)-1,h=ca(a[hb](8,10),10);if(a.toUpperCase()[y]("T")==-1)return new ff(new Date(d,e,h),b);var j=ca(a[hb](11,13),10),l=ca(a[hb](14,16),10),p=ca(a[hb](17,19),10),s=ca(a[hb](20,23),10),v=new Date(d,e,h,j,l,p,s);if(a[r]>23){var F=0,x=a.charAt(23);if(x!=="Z"){var S=ca(a[hb](24,26),10),M=ca(a[hb](27,29),10);F=S*60+M;if(x!=="-")F=-F}F-=v.getTimezoneOffset();F!=0&&v.setTime(v[wb]()+F*60000)}return new ff(v)};
D("google.gdata.DateTime.fromIso8601",G);var gf=function(a){var d=a instanceof ff,e=d?a.date:a,h=e.getFullYear()+"-"+cc(e.getMonth()+1,2)+"-"+cc(e.getDate(),2);if(d&&a.Bh())return h;return h+"T"+cc(e.getHours(),2)+":"+cc(e.getMinutes(),2)+":"+cc(e.getSeconds(),2)+"."+cc(e.getMilliseconds(),3)+E.util.getTimezoneOffsetString(e)};D("google.gdata.DateTime.toIso8601",gf);E.mimeType={};E.mimeType.ATOM="application/atom+xml";E.mimeType.HTML="text/html";E.client={};D("google.gdata.client",E.client);E.client.qc=function(a){if(!E.client.gt){E.client.gt=b;try{E.client.Ot();E.client.Nt()}catch(d){a?a(d):alert(d.message)}}};D("google.gdata.client.init",E.client.qc);E.client.gt=g;E.client.nh=function(a,d){for(var e=a[Ma]("."),h=d[Ma]("."),j=0;j<e[r]||j<h[r];j++){var l=j>=e[r]?0:k(e[j]),p=j>=h[r]?0:k(h[j]);if(l>p)return b;if(l<p)return g}return b};
E.client.Ot=function(){if(!(E.runtime[B]===E.runtime.TYPE.MD)){if(E.runtime[B]===E.runtime.TYPE.FE){var a="1.9";if(!this.nh(yd,a))aa(Error("Unsupported XULRunner version. Minimum required version is "+d+".  Continue at your own risk."))}else if(E.runtime[B]!==E.runtime.TYPE.UP&&E.runtime[B]!==E.runtime.TYPE.IG&&E.runtime[B]!==E.runtime.TYPE.OS)aa(Error("Unsupported client environment.  Continue at your own risk."));if(sd){var d="1.5";if(!this.nh(yd,d))aa(Error("Unsupported Firefox version.  Minimum required version is "+
d+".  Continue at your own risk."))}else if(rd){var e="6.0";if(!this.nh(yd,e))aa(Error("Unsupported Internet Explorer version.  Minimum required version is "+e+".  Continue at your own risk."))}else if(td){var h="523.0";if(!this.nh(yd,h))aa(Error("Unsupported WebKit version.  Minimum required version is "+h+".  Continue at your own risk."))}else aa(Error("Unsupported browser.  Continue at your own risk."))}};
E.client.Nt=function(){var a=da.google&&da.google.loader;if(a&&a.LoadFailure&&a.OriginalAppPath===da[Ra][A])aa(Error("Developer key validation failed."))};sa(E.client,{OK:200,NOT_OK:300,FOUND:302,BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,PRECONDITION_FAILED:412,INTERNAL_SERVER_ERROR:500});var jf=function(a){var d=function(h){return"string"==typeof h&&h[r]>0?h:c},e=a.match(hf);if(e){pa(this,d(e[1]));this.credentials=d(e[2]);this.domain=d(e[3]);this.port=d(e[4]);this.path=d(e[5]);this.query=d(e[6]);this.fragment=d(e[7])}},hf=/^(?:([^:\/?#]+):)?(?:\/\/(?:([^\/?#]*)@)?([^\/?#:@]*)(?::([0-9]+))?)?([^?#]+)?(?:\?([^#]*))?(?:#(.*))?$/,kf=function(a,d){var e=new jf(a),h=new jf(d);return(e.domain==c||e.domain==h.domain)&&(e[bb]==c||e[bb]==h[bb])};var lf=function(){sa(this,0);ja(this,"");oa(this,"");this.responseXML="";this.headers={}};lf[t].im=function(a,d){this[mb][a]=d};lf[t].getResponseHeader=function(a){return this[mb][a]};E.client.xmlHttpRequest={};
E.client.xmlHttpRequest.sendAsyncRequest=function(a,d,e,h,j,l){if(E.runtime[B]==E.runtime.TYPE.GM)GM_xmlhttpRequest({method:a,url:d,headers:h,data:e,onload:function(S){j(S,l)},onerror:l});else{var p=E.runtime.isIe?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest;try{p.open(a,d,b)}catch(s){if(typeof s=="string")s=Error(s);if(l)return l(s);else aa(s)}p.onreadystatechange=function(){p.readyState==4&&j(p,l)};if(h)for(var v in h){var F=h[v];Gb(F)||(F=i(F));p.setRequestHeader(v,F)}try{p.send(e||
"")}catch(x){if(typeof x=="string"){x=Error(x);x.cause=p}if(l)return l(x);else aa(x)}}};var mf=function(){this.As={}};mf[t].vb=function(a,d){this.As[a]=d};mf[t].Xf=function(a){return this.As[a]};mf[t].ag=function(a,d,e,h){var j=new te(a);j.yh("user-agent")||j.rb("user-agent",e);j.yh("alt")||j.rb("alt",d);h&&!j.yh("key")&&j.rb("key",h);return j};mf[t].ib=function(){aa(Error("subclass responsibility"))};var nf=function(){mf[z](this);this.vb(E.client.alt.ATOM,E.client.alt.ATOM);this.vb(E.client.alt.RSS,E.client.alt.RSS);this.vb(E.client.alt.JSON,E.client.alt.JSON)};Ob(nf,mf);nf[t].ib=function(a,d,e,h,j,l,p,s,v,F){E.client.xmlHttpRequest.sendAsyncRequest(a,this.ag(d,e,p,l)[Aa](),h,j,v,F)};var of=function(){mf[z](this);this.vb(E.client.alt.ATOM,E.client.alt.ATOM_IN_SCRIPT);this.vb(E.client.alt.RSS,E.client.alt.RSS_IN_SCRIPT);this.vb(E.client.alt.JSON,E.client.alt.JSON_IN_SCRIPT)};Ob(of,mf);var pf=0,qf={},sf=function(a,d){var e=d||0,h=rf(e);if(h){fa[Xa].removeChild(h.script);delete h.script;return h.continuation[z](h.self,a)}else aa(Error('script request "'+e+'" not found'))};if(typeof gdata=="undefined")gdata={};gdata.io={handleScriptLoaded:sf};of[t].ss=10000;of[t].gm="Request via script load timed out. Possible causes: feed URL is incorrect; feed requires authentication";
of[t].ag=function(a,d,e,h,j){var l=new te(a);l.rb("alt",d);l.rb("reqid",e);l.rb("user-agent",h);j&&l.rb("key",j);return l};
of[t].ib=function(a,d,e,h,j,l,p,s,v,F){var x=++pf,S=ef[Ka][cb]("script");S.src=this.ag(d,e,x,p,l)[Aa]();if(F)if(E.runtime.isIe)da.setTimeout(function(ga){var Wa=rf(ga);Wa&&F&&F(Error(this.gm))}[ob](this,x),this.ss);else S.onerror=function(ga){if(ga=="Error loading script")ga=this.gm;var Wa=new lf;sa(Wa,400);ja(Wa,ga);v(Wa,F)}[ob](this);var M={continuation:function(ga){E.util.buildNamespaceDictionaries(ga.feed||ga.entry);var Wa=new lf;sa(Wa,200);oa(Wa,ga);v(Wa,F)},self:s,script:S},N="req"+x;qf[N]=
M;ef[Ka][Xa][za](S)};var rf=function(a){var d="req"+a,e=qf[d];delete qf[d];return e};var tf=function(){mf[z](this);this.vb(E.client.alt.JSON,E.client.alt.JSON_XD)};Ob(tf,mf);
tf[t].ib=function(a,d,e,h,j,l,p,s,v,F){var x={};this.st(d,x);x.alt=e;x.body=h;if(a!="POST")j["X-HTTP-Method-Override"]=a;x["user-agent"]=p;if(l){var S="key";x[S]=l}Je(d,function(M){if(M[Za][$a]<E.client[$a].NOT_OK)if(Qb(M[Za][Pa]))oa(M[Za],c);else{oa(M[Za],M[Za][Pa][Ja](/\n/g,"\\n"));oa(M[Za],M[Za][Pa][Ja](/\r/g,"\\r"));try{oa(M[Za],pe(M[Za][Pa]))}catch(N){try{var ga=E.util.Rt(M[Za][Pa]);oa(M[Za],pe(ga))}catch(Wa){var ae=Error("Invalid JSON format. Unescaped JSON is a not supported format for attribute or text values.");
if(F)F(ae);else aa(ae)}}}else if(!M[Za].statusText)ja(M[Za],M[Za][Pa]);v(M[Za],F)},"POST",x,j)};tf[t].st=function(a,d){for(var e=a instanceof te?a.Sa():new te(a,undefined),h=e.Kp(),j=h.hb(),l=0;l<j[r];l++){var p=j[l],s=h.Ca(p);d[p]=s&&s[r]>0?s[0]:c}};da[Ra]&&da[Ra][Ba][y]("__debug")>0&&Ke(b);var uf=function(){mf[z](this);this.vb(E.client.alt.ATOM,E.client.alt.ATOM);this.vb(E.client.alt.RSS,E.client.alt.RSS);this.vb(E.client.alt.JSON,E.client.alt.JSON);this.om=""};Ob(uf,mf);uf[t].rt=function(a){if(a&&a["set-cookie"])for(var d=a["set-cookie"],e=0;e<d[r];++e){var h=d[e],j=/^S=[^;]+/,l=j[Ha](h);if(l)this.om=l[0]}};
uf[t].ib=function(a,d,e,h,j,l,p,s,v,F){d=this.ag(d,e,p,l)[Aa]();var x={},S=j.OPEN_SOCIAL_HEADERS;if(S){x=xc(S);delete j.OPEN_SOCIAL_HEADERS}if(this.om)j.cookie=this.om;j["X-If-No-Redirect"]&&delete j["X-If-No-Redirect"];x[gadgets.io.RequestParameters.HEADERS]=j;x[gadgets.io.RequestParameters.POST_DATA]=h;x[gadgets.io.RequestParameters.METHOD]=a;x[gadgets.io.RequestParameters.CONTENT_TYPE]=gadgets.io.ContentType.TEXT;var M=function(N){var ga=new lf;this.rt(N[mb]);if(N.errors&&N.errors[r]&&F)F(new Error(N.errors[0]));
else if(N.oauthError&&F)F(new Error(N.oauthErrorText));else if(N.rc&&N.rc==E.client[$a].FOUND){sa(ga,E.client[$a].FOUND);ga.im("Location",N[mb][Ra][0]);v(ga,F)}else{sa(ga,E.client[$a].OK);ja(ga,"OK");var Wa="text/xml";if(e==E.client.alt.JSON)Wa="application/json";ga.im("Content-Type",Wa);if(N.oauthApprovalUrl)oa(ga,{oauthApprovalUrl:N.oauthApprovalUrl});else if(N.text)oa(ga,N.text);v(ga,F)}};gadgets.io.makeRequest(d,Mb(M,this),x)};E.client.alt={};E.client.alt.ATOM="atom";E.client.alt.ATOM_IN_SCRIPT="atom-in-script";E.client.alt.RSS="rss";E.client.alt.RSS_IN_SCRIPT="rss-in-script";E.client.alt.JSON="json";E.client.alt.JSON_XD="json-xd";E.client.alt.JSON_IN_SCRIPT="json-in-script";var vf=function(a){this.sd=a};vf[t].nb=function(){aa(Error("Missing implementation: isAuthenticationRequired()"))};vf[t].Pa=function(){aa(Error("Missing implementation: isAuthenticated()"))};vf[t].Ra=function(){aa(Error("Missing implementation: authenticate()"))};vf[t].qb=function(){aa(Error("Missing implementation: setAuthHeaders()"))};var wf=function(a){vf[z](this,a)};wf.e(vf);wf[t].nb=function(){return g};wf[t].Ra=function(a,d){d()};wf[t].Pa=function(){return b};wf[t].qb=function(){};var xf={GOOGLE:"GOOGLE",HOSTED:"HOSTED",HOSTED_OR_GOOGLE:"HOSTED_OR_GOOGLE"};D("google.gdata.client.ClientLoginAccountType",xf);D("google.gdata.client.ClientLoginAccountType.GOOGLE","GOOGLE");D("google.gdata.client.ClientLoginAccountType.HOSTED","HOSTED");D("google.gdata.client.ClientLoginAccountType.HOSTED_OR_GOOGLE","HOSTED_OR_GOOGLE");var yf=function(a){vf[z](this,a)};yf.e(vf);yf[t].nb=function(){return this.sd.tf().username||this.sd.tf().password};
yf[t].Ra=function(a,d,e){var h=this.sd.tf(),j=h.username,l=h.password,p=h.accountType||"HOSTED_OR_GOOGLE";if(!j||!l)aa(Error("need username and password in service for authentication"));var s="Email="+ba(j)+"&Passwd="+ba(l)+"&source="+ba(this.sd.applicationName)+"&service="+ba(this.sd.serviceName)+"&accountType="+ba(p);E.client.xmlHttpRequest.sendAsyncRequest("POST",this.Xs(),s,{"content-type":"application/x-www-form-urlencoded"},this.Qs(d,e),e)};
yf[t].Pa=function(){return!this.sd.tf().username||this.Ub};yf[t].hm="/accounts/ClientLogin";yf[t].Xs=function(){return E.runtime[B]!=E.runtime.TYPE.UP&&E.runtime[B]!=E.runtime.TYPE.IG&&E.runtime[B]!=E.runtime.TYPE.OS?this.sd.nt+"://"+this.sd.mt+this.hm:ef[Ra][db]+"//"+ef[Ra].host+(ef[Ra][bb]?":"+ef[Ra][bb]:"")+this.hm};
yf[t].Qs=function(a,d){var e=this;return function(h){var j=zf;if(h[$a]==E.client[$a].FORBIDDEN){var l=Error("Login failed");o(l,j.LOGIN_FAILED);if(d)return d(l);else aa(l)}if(h[$a]>=E.client[$a].NOT_OK){l=Error("Bad authentication response status: "+h[$a]);o(l,j.BAD_STATUS);if(d)return d(l);else aa(l)}var p=h[Pa];if(!p){l=Error("No authentication token in response");o(l,j.NO_TOKEN);if(d)return d(l);else aa(l)}var s=p.match(/^Auth=(.*)/m);if(!s||!s[1]){l=Error("Malformed authentication token: "+p);
o(l,j.MALFORMED_TOKEN);if(d)return d(l);else aa(l)}e.Ub=s[1];a[z](e)}};var zf={BAD_STATUS:0,LOGIN_FAILED:1,NO_TOKEN:2,MALFORMED_TOKEN:3};yf[t].qb=function(a,d){if(this.Ub)d.Authorization="GoogleLogin auth="+this.Ub};var Af=function(a,d,e){vf[z](this,a);this.Hs=d;this.Tt=e||"GoogleLogin"};Af.e(vf);Af[t].nb=function(){return b};Af[t].Ra=function(a,d,e){if(this.Ub=Ue(this.Hs))d();else e&&e(new Error("cookie ("+this.Hs+") not available."))};Af[t].Pa=function(){return this.Ub!=c};Af[t].qb=function(a,d){if(this.Ub)d.Authorization=this.Tt+" auth="+this.Ub};var Bf=function(a){vf[z](this,a)};Bf.e(vf);Bf[t].nb=function(a){return this.Pa(a)};Bf[t].Ra=function(a,d){d()};Bf[t].Pa=function(a){a=this.cr(a);return cf.mh(a)};Bf[t].qb=function(a,d){a=this.cr(a);var e=cf.mh(a);if(e)d.Authorization="AuthSub token="+e};Bf[t].cr=function(a){var d=a[y]("?");if(d>0)a=a[hb](0,d);var e=a[y]("#");if(e>0)a=a[hb](0,e);return a};var Cf=function(a,d,e){vf[z](this,a);this.Jt=d;this.opt_params=e||{}};Ob(Cf,vf);Cf[t].nb=function(){return b};Cf[t].Ra=function(a,d){d()};Cf[t].Pa=function(){return g};Cf[t].qb=function(a,d){this.opt_params[gadgets.io.RequestParameters.AUTHORIZATION]=this.Jt;d.OPEN_SOCIAL_HEADERS=this.opt_params};var Df=function(a,d){E.client.qc();this.serviceName=a;this.applicationName=d;this.Xt=(new Date)[wb]()+"-"+E.util.getRandomInt(100,999);this.fb=new this.Lg(this);this.Qb={};this.Qb[E.client.alt.ATOM]=b;this.et={"X-If-No-Redirect":"1"};this.km=this.qg=this.Ks=c;this.Jg(g)},Ef;D("google.gdata.client.Service",Df);Df[t].Lg=wf;Df[t].lr=function(a){this.Ks=a};D("google.gdata.client.Service.prototype.setDeveloperKey",Df[t].lr);Df[t].Kg=function(a){return this.Qb[a]};
D("google.gdata.client.Service.prototype.supportsAlt",Df[t].Kg);Df[t].Gg=function(a,d){this.Qb[a]=d};D("google.gdata.client.Service.prototype.setAltSupport",Df[t].Gg);Df[t].Eh=function(){return this.Yt};D("google.gdata.client.Service.prototype.isXd2Supported",Df[t].Eh);Df[t].Jg=function(a){this.Yt=a};D("google.gdata.client.Service.prototype.setXd2Supported",Df[t].Jg);Df[t].sc=function(){return g};Df[t].xs=new nf;Df[t].us=new of;Df[t].ws=new tf;Df[t].ps=new uf;Df[t].Ss=function(){return ef[Ra][A]};
Df[t].at=function(a,d){return E.runtime[B]!=E.runtime.TYPE.UP&&E.runtime[B]!=E.runtime.TYPE.IG&&E.runtime[B]!=E.runtime.TYPE.OS?this.Yp(a,d):kf(a,this.Ss())?this.Yp(a,d):this.Rs(a,d)};Df[t].Yp=function(){return this.xs};Df[t].Rs=function(a,d){if(E.runtime[B]==E.runtime.TYPE.OS)return this.ps;if(d=="GET"&&!this.sc(a))return this.us;if(this.Eh())if(this.dt())return this.ws;else{var e="An image of the same domain is required on this page for authenticated reads and all writes.";aa(Error(e))}else aa(Error("no suitable transport"))};
Df[t].dt=function(){if(Ef==undefined)if(E.runtime[B]==E.runtime.TYPE.UP){for(var a=fa.getElementsByTagName("img"),d=0;d<a[r];d++){var e=a[d];if(Ee(e.src,da[Ra][A]))return Ef=b}Ef=g}else Ef=b;return Ef};Df[t].fr=function(a,d,e,h,j,l){this.Fg(a,d,e,h,j,l,b)};
Df[t].Fg=function(a,d,e,h,j,l,p){this.sc(d)&&this.fb.qb(d,h);var s=this.at(d,a),v=this.Kg(s.Xf(E.client.alt.JSON))?E.client.alt.JSON:this.Kg(s.Xf(E.client.alt.ATOM))?E.client.alt.ATOM:c;if(v){var F=v==E.client.alt.JSON?function(N,ga,Wa){if(typeof N[Pa]=="string"){var ae=N.getResponseHeader("Content-Type"),Mg=ae&&ae[y]("xml")>0?E.util.convertXmlTextToJavaScript(N[Pa]):E.util.convertJsonTextToJavaScript(N[Pa]);return ga(Mg,Wa)}return ga(N[Pa],Wa)}:function(N,ga,Wa){if(typeof N[Pa]=="string")return ga(E.util.convertXmlTextToJavaScript(N[Pa]),
Wa);return ga(N[Pa],Wa)};this.Bt(s,a,d,v,e,h,F,j,l,p)}else{var x=s.Xf(E.client.alt.JSON),S=s.Xf(E.client.alt.ATOM),M="";if(x)M+=x;if(S){if(M)M+=" or ";M+=S}M=M?": "+M:".";aa(Error("service does not support alt required by transport"+M))}};
Df[t].Bt=function(a,d,e,h,j,l,p,s,v,F){var x=this,S=a.Xf(h),M=ba(this.applicationName+" GData-JavaScript/"+(da.GData_API_Version||"dev")+" "+this.Xt);a.ib(d,e,S,j,l,this.Ks,M,this,function(N,ga){if(N[$a]<E.client[$a].NOT_OK)return p(N,s,ga);else if(F&&N[$a]==E.client[$a].PRECONDITION_FAILED){var Wa=N.getResponseHeader("X-Redirect-Location");return x.Fg(d,Wa,j,l,s,ga,g)}else if(F&&N[$a]==E.client[$a].FOUND){Wa=N.getResponseHeader("Location");return x.Fg(d,Wa,j,l,s,ga,g)}else if(F&&N[$a]==E.client[$a].INTERNAL_SERVER_ERROR)return x.Fg(d,
e,j,l,s,ga,g);else if(N[$a]==E.client[$a].BAD_REQUEST&&N[Pa]=="Invalid Feed Type"){this.Gg(E.client.alt.JSON,g);return x.fr(d,e,j,l,function(){x.Gg(E.client.alt.JSON,b);s[lb](this,arguments)},ga)}else{var ae=N.statusText;if(N[$a]==E.client[$a].UNAUTHORIZED&&N.statusText=="OK")ae="Authorization required";var Mg=Error(ae);Mg.cause=N;if(N.responseHeaders)Mg.statusTextContentType=N.responseHeaders["Content-Type"];if(ga)return ga(Mg)}}[ob](this),v)};
Df[t].M=function(a,d,e,h,j){var l=typeof a=="string"?a:a.Oa();return this.Xp(l,d,e,{feedClass:h,authenticationRequired:j})};D("google.gdata.client.Service.prototype.getFeed",Df[t].M);Df[t].O=function(a,d,e,h,j){return this.Xp(a,d,e,{entryClass:h,authenticationRequired:j})};D("google.gdata.client.Service.prototype.getEntry",Df[t].O);Df[t].Xp=function(a,d,e,h){if((h&&h.authenticationRequired||this.sc(a))&&!this.fb.Pa(a)){var j=this;this.fb.Ra(a,function(){j.Tq(a,d,e,h)},e)}else this.Tq(a,d,e,h)};
Df[t].Tq=function(a,d,e,h){return this.Eg("GET",a,"",d,e,h)};Df[t].od=function(a,d,e,h,j){if(this.sc(a)&&!this.fb.Pa(a)){var l=this;this.fb.Ra(a,function(){l.Uq(a,d,e,h,j)},h)}else this.Uq(a,d,e,h,j)};D("google.gdata.client.Service.prototype.insertEntry",Df[t].od);Df[t].Uq=function(a,d,e,h,j){if(!d.jd)d.jd="http://www.w3.org/2005/Atom";var l=E.util.convertEntryToAtom(d,this.km);if(!j&&d[u]!==m)j=d[u];this.Eg("POST",a,l,e,h,{entryClass:j})};
Df[t].Ad=function(a,d,e,h,j){if(this.sc(a)&&!this.fb.Pa(a)){var l=this;this.fb.Ra(a,function(){l.ks(a,d,e,h,j)},h)}else this.ks(a,d,e,h,j)};D("google.gdata.client.Service.prototype.updateEntry",Df[t].Ad);Df[t].ks=function(a,d,e,h,j){if(!j&&d[u]!==m)j=d[u];var l=E.util.convertEntryToAtom(d,this.km);this.Eg("PUT",a,l,e,h,{entryClass:j})};Df[t].kd=function(a,d,e){if(this.sc(a)&&!this.fb.Pa(a)){var h=this;this.fb.Ra(a,function(){h.sm(a,d,e)},e)}else this.sm(a,d,e)};
D("google.gdata.client.Service.prototype.deleteEntry",Df[t].kd);Df[t].sm=function(a,d,e){this.Eg("DELETE",a,"",d,e)};
Df[t].Eg=function(a,d,e,h,j,l){var p=E.util.copy(this.et);if(e){p["Content-Length"]=e[r];p["Content-Type"]=E.mimeType.ATOM+"; charset=UTF-8"}else p["Content-Length"]=0;if((a=="PUT"||a=="DELETE"&&!E.runtime.isIe&&!E.runtime.isSafari)&&E.runtime[B]!=E.runtime.TYPE.OS){p["X-HTTP-Method-Override"]=a;a="POST"}else delete p["X-HTTP-Method-Override"];var s=this;this.fr(a,d,e,p,function(v){if(v&&v.feed){var F=l&&l.feedClass||s.feedClass;v.feed.$service_=s;if(F)v.feed=E.util.mutateTo(v.feed,F);var x=v.feed.entry;
if(x)for(var S=0;S<x[r];S++){x[S].$service_=s;if(s.qg)na(x[S],s.qg(x[S][Oa]))}}else if(v&&v.entry){var M=l&&l.entryClass||s.entryClass;if(M)v.entry=E.util.mutateTo(v.entry,M);v.entry.$service_=s;if(s.qg)na(v.entry,s.qg(v.entry[Oa]))}h[lb](this,arguments)},j)};Df[t].vr=function(a){for(var d in a)this.et[d]=a[d]};D("google.gdata.client.Service.prototype.setHeaders",Df[t].vr);var Ff=function(a,d){Df[z](this,a,d);this.ys=this.tt=this.Ht=c;this.Qb[E.client.alt.ATOM]=b;this.Qb[E.client.alt.ATOM_IN_SCRIPT]=b;this.Qb[E.client.alt.RSS]=b;this.Qb[E.client.alt.RSS_IN_SCRIPT]=b;this.Qb[E.client.alt.JSON]=b;this.Qb[E.client.alt.JSON_IN_SCRIPT]=b;this.Qb[E.client.alt.JSON_XD]=b;this.Jg(b)};D("google.gdata.client.GoogleService",Ff);Ff.e(Df);Ff[t].Lg=Bf;Ff[t].nt="https";Ff[t].mt="www.google.com";Ff[t].tf=function(){return{username:this.Ht,password:this.tt,accountType:this.ys}};
D("google.gdata.client.GoogleService.prototype.getUserCredentials",Ff[t].tf);Ff[t].gs=function(a,d,e){this.Ht=a;this.tt=d;this.ys=e||c;this.fb=new yf(this)};D("google.gdata.client.GoogleService.prototype.setUserCredentials",Ff[t].gs);Ff[t].hr=function(a,d){this.fb=new Af(this,a,d)};D("google.gdata.client.GoogleService.prototype.setAuthenticationCookie",Ff[t].hr);Ff[t].zi=function(a,d){this.fb=new Cf(this,a,d)};D("google.gdata.client.GoogleService.prototype.setGadgetsAuthentication",Ff[t].zi);
Ff[t].ms=function(a,d){d=d||{};d[gadgets.io.RequestParameters.OAUTH_SERVICE_NAME]=a;this.zi(gadgets.io.AuthorizationType.OAUTH,d)};D("google.gdata.client.GoogleService.prototype.useOAuth",Ff[t].ms);Ff[t].sc=function(a){return this.fb.nb(a)};var Gf=function(a,d){Ff[z](this,a,d);this.qg=function(e){return this.Gs(e.$t)};this.km=this.Ds[ob](this)};D("google.gdata.client.FeedServerService",Gf);Gf.e(Ff);Gf[t].Gs=function(a){return a?this.ph(E.util.convertXmlTextToJavaScript(a)):c};Gf[t].ph=function(a){return a.$t!=undefined?a.$t:Eb(a)?this.Cs(a):Ib(a)?this.Es(a):a};Gf[t].Cs=function(a){for(var d=[],e=0;e<a[r];e++)d[e]=this.ph(a[e]);return d};Gf[t].Es=function(a){var d={};for(var e in a)d[e]=this.ph(a[e]);return d};
Gf[t].Ds=function(a,d,e){e[q]("<",a," type='application/xml'",">");this.mm("entity",d.entity,e);e[q]("</",a,">")};Gf[t].nm=function(a,d,e,h){var j=Db(d);if(j=="string"||j=="number"||j=="boolean")e[q]("<",a,h?" repeatable='true'>":">",E.util.escapeXmlContent(d),"</",a,">");else if(j=="array")this.Fs(a,d,e);else j=="object"?this.mm(a,d,e,h):e[q]("<",a,"/>")};Gf[t].mm=function(a,d,e,h){e[q]("<",a,h?" repeatable='true'>":">");for(var j in d)this.nm(j,d[j],e,g);e[q]("</",a,">")};
Gf[t].Fs=function(a,d,e){for(var h=0;h<d[r];h++)this.nm(a,d[h],e,h==0)};var Hf=function(a){this.feedUri=a;this.Zq={};this.Yq=E.util.copy(this.qs)};D("google.gdata.client.Query",Hf);Hf[t].qs={alt:{defaultValue:E.client.alt.ATOM}};Hf[t].v=function(a,d){this.Yq[a]=d};D("google.gdata.client.Query.prototype.setParamDef",Hf[t].v);Hf[t].d=function(a,d){this.Zq[a]=d};D("google.gdata.client.Query.prototype.setParam",Hf[t].d);
Hf[t].Me=function(){var a=[];for(var d in this.Zq){var e=this.c(d);if(e!==c){var h=this.Yq[d];if(h!==undefined&&h.decorator)e=h.decorator(e);else if(e instanceof ff)e=gf(e);a[q](d+"="+ba(e))}}var j=a[xb]("&");return j[r]?"?"+j:""};D("google.gdata.client.Query.prototype.getPath",Hf[t].Me);Hf[t].Oa=function(){return this.feedUri+this.Me()};D("google.gdata.client.Query.prototype.getUri",Hf[t].Oa);
Hf[t].c=function(a){var d=this.Zq[a],e=this.Yq[a];if(d!==undefined&&(e===undefined||d!==e.defaultValue))return d;return c};D("google.gdata.client.Query.prototype.getParam",Hf[t].c);E.onLoad=function(){df()};D("google.gdata.onLoad",E.onLoad);Hb(Ab.GData_API_callback)&&Ab.GData_API_callback();

E.mediarss={};E.mediarss.namespace={};E.mediarss.namespace.MEDIA="http://search.yahoo.com/mrss/";var bj=function(a){if(a){this.$t=a[Oa];xa(this,a[tb]);pa(this,a[Qa])}else{this.$t=this.$t;xa(this,this[tb]);pa(this,this[Qa])}};D("google.gdata.mediarss.MediaCategory",bj);bj[t].s=function(){return this.$t};D("google.gdata.mediarss.MediaCategory.prototype.getContent",bj[t].s);bj[t].r=function(a){this.$t=a};D("google.gdata.mediarss.MediaCategory.prototype.setContent",bj[t].r);bj[t].I=function(){return this[tb]};D("google.gdata.mediarss.MediaCategory.prototype.getLabel",bj[t].I);
bj[t].J=function(a){xa(this,a)};D("google.gdata.mediarss.MediaCategory.prototype.setLabel",bj[t].J);bj[t].ya=function(){return this[Qa]};D("google.gdata.mediarss.MediaCategory.prototype.getScheme",bj[t].ya);bj[t].na=function(a){pa(this,a)};D("google.gdata.mediarss.MediaCategory.prototype.setScheme",bj[t].na);var cj=function(a){if(a){this.$t=a[Oa];this.url=a.url}else{this.$t=this.$t;this.url=this.url}};D("google.gdata.mediarss.MediaCopyright",cj);cj[t].s=function(){return this.$t};D("google.gdata.mediarss.MediaCopyright.prototype.getContent",cj[t].s);cj[t].r=function(a){this.$t=a};D("google.gdata.mediarss.MediaCopyright.prototype.setContent",cj[t].r);cj[t].Ja=function(){return this.url};D("google.gdata.mediarss.MediaCopyright.prototype.getUrl",cj[t].Ja);cj[t].La=function(a){this.url=a};
D("google.gdata.mediarss.MediaCopyright.prototype.setUrl",cj[t].La);var dj=function(a){if(a){this.$t=a[Oa];this.role=a.role;pa(this,a[Qa])}else{this.$t=this.$t;this.role=this.role;pa(this,this[Qa])}};D("google.gdata.mediarss.MediaCredit",dj);dj[t].s=function(){return this.$t};D("google.gdata.mediarss.MediaCredit.prototype.getContent",dj[t].s);dj[t].r=function(a){this.$t=a};D("google.gdata.mediarss.MediaCredit.prototype.setContent",dj[t].r);dj[t].df=function(){return this.role};D("google.gdata.mediarss.MediaCredit.prototype.getRole",dj[t].df);
dj[t].xd=function(a){this.role=a};D("google.gdata.mediarss.MediaCredit.prototype.setRole",dj[t].xd);dj[t].ya=function(){return this[Qa]};D("google.gdata.mediarss.MediaCredit.prototype.getScheme",dj[t].ya);dj[t].na=function(a){pa(this,a)};D("google.gdata.mediarss.MediaCredit.prototype.setScheme",dj[t].na);var ej=function(a){if(a){this.$t=a[Oa];o(this,a[B])}else{this.$t=this.$t;o(this,this[B])}};D("google.gdata.mediarss.MediaDescription",ej);ej[t].s=function(){return this.$t};D("google.gdata.mediarss.MediaDescription.prototype.getContent",ej[t].s);ej[t].r=function(a){this.$t=a};D("google.gdata.mediarss.MediaDescription.prototype.setContent",ej[t].r);ej[t].o=function(){return this[B]};D("google.gdata.mediarss.MediaDescription.prototype.getType",ej[t].o);ej[t].l=function(a){o(this,a)};
D("google.gdata.mediarss.MediaDescription.prototype.setType",ej[t].l);D("google.gdata.mediarss.MediaDescription.TYPE_HTML","html");D("google.gdata.mediarss.MediaDescription.TYPE_PLAIN","plain");var fj=function(a){if(a){this.algo=a.algo;this.$t=a[Oa]}else{this.algo=this.algo;this.$t=this.$t}};D("google.gdata.mediarss.MediaHash",fj);fj[t].Em=function(){return this.algo};D("google.gdata.mediarss.MediaHash.prototype.getAlgo",fj[t].Em);fj[t].gr=function(a){this.algo=a};D("google.gdata.mediarss.MediaHash.prototype.setAlgo",fj[t].gr);D("google.gdata.mediarss.MediaHash.ALGO_MD5","md5");D("google.gdata.mediarss.MediaHash.ALGO_SHA_1","sha-1");fj[t].s=function(){return this.$t};
D("google.gdata.mediarss.MediaHash.prototype.getContent",fj[t].s);fj[t].r=function(a){this.$t=a};D("google.gdata.mediarss.MediaHash.prototype.setContent",fj[t].r);var gj=function(a){this.$t=a?a[Oa]:this.$t};D("google.gdata.mediarss.MediaKeywords",gj);gj[t].s=function(){return this.$t};D("google.gdata.mediarss.MediaKeywords.prototype.getContent",gj[t].s);gj[t].r=function(a){this.$t=a};D("google.gdata.mediarss.MediaKeywords.prototype.setContent",gj[t].r);var hj=function(a){if(a){this.Ka(a[ub]);this.url=a.url;this.Ma(a[Ia])}else{ya(this,this[ub]);this.url=this.url;ma(this,this[Ia])}};D("google.gdata.mediarss.MediaPlayer",hj);hj[t].Ta=function(){return this[ub]===undefined?undefined:k(this[ub])};D("google.gdata.mediarss.MediaPlayer.prototype.getHeight",hj[t].Ta);hj[t].Ka=function(a){ya(this,a===undefined?undefined:i(a))};D("google.gdata.mediarss.MediaPlayer.prototype.setHeight",hj[t].Ka);hj[t].Ja=function(){return this.url};
D("google.gdata.mediarss.MediaPlayer.prototype.getUrl",hj[t].Ja);hj[t].La=function(a){this.url=a};D("google.gdata.mediarss.MediaPlayer.prototype.setUrl",hj[t].La);hj[t].Ua=function(){return this[Ia]===undefined?undefined:k(this[Ia])};D("google.gdata.mediarss.MediaPlayer.prototype.getWidth",hj[t].Ua);hj[t].Ma=function(a){ma(this,a===undefined?undefined:i(a))};D("google.gdata.mediarss.MediaPlayer.prototype.setWidth",hj[t].Ma);var ij=function(a){if(a){this.$t=a[Oa];pa(this,a[Qa])}else{this.$t=this.$t;pa(this,this[Qa])}};D("google.gdata.mediarss.MediaRating",ij);ij[t].s=function(){return this.$t};D("google.gdata.mediarss.MediaRating.prototype.getContent",ij[t].s);ij[t].r=function(a){this.$t=a};D("google.gdata.mediarss.MediaRating.prototype.setContent",ij[t].r);ij[t].ya=function(){return this[Qa]};D("google.gdata.mediarss.MediaRating.prototype.getScheme",ij[t].ya);ij[t].na=function(a){pa(this,a)};
D("google.gdata.mediarss.MediaRating.prototype.setScheme",ij[t].na);D("google.gdata.mediarss.MediaRating.SCHEME_DEFAULT_SCHEME","urn:simple");var jj=function(a){if(a){this.$t=a[Oa];this.relationship=a.relationship;o(this,a[B])}else{this.$t=this.$t;this.relationship=this.relationship;o(this,this[B])}};D("google.gdata.mediarss.MediaRestriction",jj);jj[t].s=function(){return this.$t};D("google.gdata.mediarss.MediaRestriction.prototype.getContent",jj[t].s);jj[t].r=function(a){this.$t=a};D("google.gdata.mediarss.MediaRestriction.prototype.setContent",jj[t].r);jj[t].Sp=function(){return this.relationship};
D("google.gdata.mediarss.MediaRestriction.prototype.getRelationship",jj[t].Sp);jj[t].Wr=function(a){this.relationship=a};D("google.gdata.mediarss.MediaRestriction.prototype.setRelationship",jj[t].Wr);D("google.gdata.mediarss.MediaRestriction.RELATIONSHIP_ALLOW","allow");D("google.gdata.mediarss.MediaRestriction.RELATIONSHIP_DENY","deny");jj[t].o=function(){return this[B]};D("google.gdata.mediarss.MediaRestriction.prototype.getType",jj[t].o);jj[t].l=function(a){o(this,a)};
D("google.gdata.mediarss.MediaRestriction.prototype.setType",jj[t].l);D("google.gdata.mediarss.MediaRestriction.TYPE_COUNTRY","country");D("google.gdata.mediarss.MediaRestriction.TYPE_URI","uri");var kj=function(a){if(a){this.$t=a[Oa];this.end=a.end;this.lang=a[Ga];this.start=a.start;o(this,a[B])}else{this.$t=this.$t;this.end=this.end;this.lang=this[Ga];this.start=this.start;o(this,this[B])}};D("google.gdata.mediarss.MediaText",kj);kj[t].s=function(){return this.$t};D("google.gdata.mediarss.MediaText.prototype.getContent",kj[t].s);kj[t].r=function(a){this.$t=a};D("google.gdata.mediarss.MediaText.prototype.setContent",kj[t].r);kj[t].Dn=function(){return this.end};
D("google.gdata.mediarss.MediaText.prototype.getEnd",kj[t].Dn);kj[t].setEnd=function(a){this.end=a};D("google.gdata.mediarss.MediaText.prototype.setEnd",kj[t].setEnd);kj[t].Ge=function(){return this[Ga]};D("google.gdata.mediarss.MediaText.prototype.getLang",kj[t].Ge);kj[t].Gf=function(a){this.lang=a};D("google.gdata.mediarss.MediaText.prototype.setLang",kj[t].Gf);kj[t].nq=function(){return this.start};D("google.gdata.mediarss.MediaText.prototype.getStart",kj[t].nq);
kj[t].setStart=function(a){this.start=a};D("google.gdata.mediarss.MediaText.prototype.setStart",kj[t].setStart);kj[t].o=function(){return this[B]};D("google.gdata.mediarss.MediaText.prototype.getType",kj[t].o);kj[t].l=function(a){o(this,a)};D("google.gdata.mediarss.MediaText.prototype.setType",kj[t].l);D("google.gdata.mediarss.MediaText.TYPE_HTML","html");D("google.gdata.mediarss.MediaText.TYPE_PLAIN","plain");var lj=function(a){if(a){this.Ka(a[ub]);this.time=a.time;this.url=a.url;this.Ma(a[Ia])}else{ya(this,this[ub]);this.time=this.time;this.url=this.url;ma(this,this[Ia])}};D("google.gdata.mediarss.MediaThumbnail",lj);lj[t].Ta=function(){return this[ub]===undefined?undefined:k(this[ub])};D("google.gdata.mediarss.MediaThumbnail.prototype.getHeight",lj[t].Ta);lj[t].Ka=function(a){ya(this,a===undefined?undefined:i(a))};D("google.gdata.mediarss.MediaThumbnail.prototype.setHeight",lj[t].Ka);lj[t].getTime=function(){return this.time};
D("google.gdata.mediarss.MediaThumbnail.prototype.getTime",lj[t][wb]);lj[t].setTime=function(a){this.time=a};D("google.gdata.mediarss.MediaThumbnail.prototype.setTime",lj[t].setTime);lj[t].Ja=function(){return this.url};D("google.gdata.mediarss.MediaThumbnail.prototype.getUrl",lj[t].Ja);lj[t].La=function(a){this.url=a};D("google.gdata.mediarss.MediaThumbnail.prototype.setUrl",lj[t].La);lj[t].Ua=function(){return this[Ia]===undefined?undefined:k(this[Ia])};
D("google.gdata.mediarss.MediaThumbnail.prototype.getWidth",lj[t].Ua);lj[t].Ma=function(a){ma(this,a===undefined?undefined:i(a))};D("google.gdata.mediarss.MediaThumbnail.prototype.setWidth",lj[t].Ma);var mj=function(a){if(a){this.$t=a[Oa];o(this,a[B])}else{this.$t=this.$t;o(this,this[B])}};D("google.gdata.mediarss.MediaTitle",mj);mj[t].s=function(){return this.$t};D("google.gdata.mediarss.MediaTitle.prototype.getContent",mj[t].s);mj[t].r=function(a){this.$t=a};D("google.gdata.mediarss.MediaTitle.prototype.setContent",mj[t].r);mj[t].o=function(){return this[B]};D("google.gdata.mediarss.MediaTitle.prototype.getType",mj[t].o);mj[t].l=function(a){o(this,a)};
D("google.gdata.mediarss.MediaTitle.prototype.setType",mj[t].l);D("google.gdata.mediarss.MediaTitle.TYPE_HTML","html");D("google.gdata.mediarss.MediaTitle.TYPE_PLAIN","plain");var Q=function(a){if(!C(this.Ea))this.Ea=bj;if(!C(this.Ed))this.Ed=cj;if(!C(this.Gd))this.Gd=dj;if(!C(this.Id))this.Id=ej;if(!C(this.Md))this.Md=fj;if(!C(this.Od))this.Od=gj;if(!C(this.Td))this.Td=hj;if(!C(this.Vd))this.Vd=ij;if(!C(this.Xd))this.Xd=jj;if(!C(this.ae))this.ae=kj;if(!C(this.be))this.be=lj;if(!C(this.pa))this.pa=mj;if(a){this.Rh(a.bitrate);this.ka(a.categories);this.Th(a.channels);this.yc(a.copyright);this.Ac(a.credits);this.Cc(a.description);this.ji(a.duration);this.expression=a.expression;
this.ui(a.fileSize);this.xi(a.framerate);this.Gc(a[Ba]);this.Ka(a[ub]);this.Mi(a.isDefault);this.Hc(a.keywords);this.language=a.language;this.medium=a.medium;this.Mc(a.player);this.Nc(a.ratings);this.Pc(a.restrictions);this.Dj(a.samplingrate);this.bd(a.texts);this.cd(a.thumbnails);this.K(a[Da]);o(this,a[B]);this.url=a.url;this.Ma(a[Ia])}else{this.bitrate=this.bitrate;if(this.media$category)for(var d=this.media$category,e=0;e<d[r];e++)this.media$category[e]=E.util.mutateTo(d[e],this.Ea);else this.media$category=
[];this.channels=this.channels;this.media$copyright=E.util.mutateTo(this.media$copyright,this.Ed);if(this.media$credit){d=this.media$credit;for(e=0;e<d[r];e++)this.media$credit[e]=E.util.mutateTo(d[e],this.Gd)}else this.media$credit=[];this.media$description=E.util.mutateTo(this.media$description,this.Id);this.duration=this.duration;this.expression=this.expression;this.fileSize=this.fileSize;this.framerate=this.framerate;this.media$hash=E.util.mutateTo(this.media$hash,this.Md);ya(this,this[ub]);this.isDefault=
this.isDefault;this.media$keywords=E.util.mutateTo(this.media$keywords,this.Od);this.language=this.language;this.medium=this.medium;this.media$player=E.util.mutateTo(this.media$player,this.Td);if(this.media$rating){d=this.media$rating;for(e=0;e<d[r];e++)this.media$rating[e]=E.util.mutateTo(d[e],this.Vd)}else this.media$rating=[];if(this.media$restriction){d=this.media$restriction;for(e=0;e<d[r];e++)this.media$restriction[e]=E.util.mutateTo(d[e],this.Xd)}else this.media$restriction=[];this.samplingrate=
this.samplingrate;if(this.media$text){d=this.media$text;for(e=0;e<d[r];e++)this.media$text[e]=E.util.mutateTo(d[e],this.ae)}else this.media$text=[];if(this.media$thumbnail){d=this.media$thumbnail;for(e=0;e<d[r];e++)this.media$thumbnail[e]=E.util.mutateTo(d[e],this.be)}else this.media$thumbnail=[];this.media$title=E.util.mutateTo(this.media$title,this.pa);o(this,this[B]);this.url=this.url;ma(this,this[Ia])}};D("google.gdata.mediarss.MediaContent",Q);
Q[t].Pm=function(){return this.bitrate===undefined?undefined:k(this.bitrate)};D("google.gdata.mediarss.MediaContent.prototype.getBitrate",Q[t].Pm);Q[t].Rh=function(a){this.bitrate=a===undefined?undefined:i(a)};D("google.gdata.mediarss.MediaContent.prototype.setBitrate",Q[t].Rh);Q[t].Ga=function(){return this.media$category};D("google.gdata.mediarss.MediaContent.prototype.getCategories",Q[t].Ga);Q[t].ka=function(a){this.media$category=[];if(a)for(var d=0;d<a[r];d++)this.ia(a[d])};
D("google.gdata.mediarss.MediaContent.prototype.setCategories",Q[t].ka);Q[t].ia=function(a){if(a[u]===m)a=new this.Ea(a);this.media$category[q](a)};D("google.gdata.mediarss.MediaContent.prototype.addCategory",Q[t].ia);Q[t].Wm=function(){return this.channels===undefined?undefined:k(this.channels)};D("google.gdata.mediarss.MediaContent.prototype.getChannels",Q[t].Wm);Q[t].Th=function(a){this.channels=a===undefined?undefined:i(a)};D("google.gdata.mediarss.MediaContent.prototype.setChannels",Q[t].Th);
Q[t].re=function(){return this.media$copyright};D("google.gdata.mediarss.MediaContent.prototype.getCopyright",Q[t].re);Q[t].yc=function(a){if(a&&a[u]===m)a=new this.Ed(a);this.media$copyright=a};D("google.gdata.mediarss.MediaContent.prototype.setCopyright",Q[t].yc);Q[t].te=function(){return this.media$credit};D("google.gdata.mediarss.MediaContent.prototype.getCredits",Q[t].te);Q[t].Ac=function(a){this.media$credit=[];if(a)for(var d=0;d<a[r];d++)this.Yb(a[d])};
D("google.gdata.mediarss.MediaContent.prototype.setCredits",Q[t].Ac);Q[t].Yb=function(a){if(a[u]===m)a=new this.Gd(a);this.media$credit[q](a)};D("google.gdata.mediarss.MediaContent.prototype.addCredit",Q[t].Yb);Q[t].xe=function(){return this.media$description};D("google.gdata.mediarss.MediaContent.prototype.getDescription",Q[t].xe);Q[t].Cc=function(a){if(a&&a[u]===m)a=new this.Id(a);this.media$description=a};D("google.gdata.mediarss.MediaContent.prototype.setDescription",Q[t].Cc);
Q[t].yn=function(){return this.duration===undefined?undefined:k(this.duration)};D("google.gdata.mediarss.MediaContent.prototype.getDuration",Q[t].yn);Q[t].ji=function(a){this.duration=a===undefined?undefined:i(a)};D("google.gdata.mediarss.MediaContent.prototype.setDuration",Q[t].ji);Q[t].Kn=function(){return this.expression};D("google.gdata.mediarss.MediaContent.prototype.getExpression",Q[t].Kn);Q[t].setExpression=function(a){this.expression=a};
D("google.gdata.mediarss.MediaContent.prototype.setExpression",Q[t].setExpression);D("google.gdata.mediarss.MediaContent.EXPRESSION_FULL","full");D("google.gdata.mediarss.MediaContent.EXPRESSION_NONSTOP","nonstop");D("google.gdata.mediarss.MediaContent.EXPRESSION_SAMPLE","sample");Q[t].Qn=function(){return this.fileSize===undefined?undefined:k(this.fileSize)};D("google.gdata.mediarss.MediaContent.prototype.getFileSize",Q[t].Qn);Q[t].ui=function(a){this.fileSize=a===undefined?undefined:i(a)};
D("google.gdata.mediarss.MediaContent.prototype.setFileSize",Q[t].ui);Q[t].Vn=function(){return this.framerate===undefined?undefined:k(this.framerate)};D("google.gdata.mediarss.MediaContent.prototype.getFramerate",Q[t].Vn);Q[t].xi=function(a){this.framerate=a===undefined?undefined:i(a)};D("google.gdata.mediarss.MediaContent.prototype.setFramerate",Q[t].xi);Q[t].De=function(){return this.media$hash};D("google.gdata.mediarss.MediaContent.prototype.getHash",Q[t].De);
Q[t].Gc=function(a){if(a&&a[u]===m)a=new this.Md(a);this.media$hash=a};D("google.gdata.mediarss.MediaContent.prototype.setHash",Q[t].Gc);Q[t].Ta=function(){return this[ub]===undefined?undefined:k(this[ub])};D("google.gdata.mediarss.MediaContent.prototype.getHeight",Q[t].Ta);Q[t].Ka=function(a){ya(this,a===undefined?undefined:i(a))};D("google.gdata.mediarss.MediaContent.prototype.setHeight",Q[t].Ka);Q[t].uo=function(){return this.isDefault===undefined?undefined:this.isDefault==="true"};
D("google.gdata.mediarss.MediaContent.prototype.getIsDefault",Q[t].uo);Q[t].Mi=function(a){this.isDefault=a===undefined?undefined:i(a)};D("google.gdata.mediarss.MediaContent.prototype.setIsDefault",Q[t].Mi);Q[t].Fe=function(){return this.media$keywords};D("google.gdata.mediarss.MediaContent.prototype.getKeywords",Q[t].Fe);Q[t].Hc=function(a){if(a&&a[u]===m)a=new this.Od(a);this.media$keywords=a};D("google.gdata.mediarss.MediaContent.prototype.setKeywords",Q[t].Hc);Q[t].Fo=function(){return this.language};
D("google.gdata.mediarss.MediaContent.prototype.getLanguage",Q[t].Fo);Q[t].Cr=function(a){this.language=a};D("google.gdata.mediarss.MediaContent.prototype.setLanguage",Q[t].Cr);Q[t].Vo=function(){return this.medium};D("google.gdata.mediarss.MediaContent.prototype.getMedium",Q[t].Vo);Q[t].Gr=function(a){this.medium=a};D("google.gdata.mediarss.MediaContent.prototype.setMedium",Q[t].Gr);Q[t].Ne=function(){return this.media$player};D("google.gdata.mediarss.MediaContent.prototype.getPlayer",Q[t].Ne);
Q[t].Mc=function(a){if(a&&a[u]===m)a=new this.Td(a);this.media$player=a};D("google.gdata.mediarss.MediaContent.prototype.setPlayer",Q[t].Mc);Q[t].Pe=function(){return this.media$rating};D("google.gdata.mediarss.MediaContent.prototype.getRatings",Q[t].Pe);Q[t].Nc=function(a){this.media$rating=[];if(a)for(var d=0;d<a[r];d++)this.cc(a[d])};D("google.gdata.mediarss.MediaContent.prototype.setRatings",Q[t].Nc);Q[t].cc=function(a){if(a[u]===m)a=new this.Vd(a);this.media$rating[q](a)};
D("google.gdata.mediarss.MediaContent.prototype.addRating",Q[t].cc);Q[t].Ue=function(){return this.media$restriction};D("google.gdata.mediarss.MediaContent.prototype.getRestrictions",Q[t].Ue);Q[t].Pc=function(a){this.media$restriction=[];if(a)for(var d=0;d<a[r];d++)this.ec(a[d])};D("google.gdata.mediarss.MediaContent.prototype.setRestrictions",Q[t].Pc);Q[t].ec=function(a){if(a[u]===m)a=new this.Xd(a);this.media$restriction[q](a)};D("google.gdata.mediarss.MediaContent.prototype.addRestriction",Q[t].ec);
Q[t].Zp=function(){return this.samplingrate===undefined?undefined:k(this.samplingrate)};D("google.gdata.mediarss.MediaContent.prototype.getSamplingrate",Q[t].Zp);Q[t].Dj=function(a){this.samplingrate=a===undefined?undefined:i(a)};D("google.gdata.mediarss.MediaContent.prototype.setSamplingrate",Q[t].Dj);Q[t].nf=function(){return this.media$text};D("google.gdata.mediarss.MediaContent.prototype.getTexts",Q[t].nf);Q[t].bd=function(a){this.media$text=[];if(a)for(var d=0;d<a[r];d++)this.fc(a[d])};
D("google.gdata.mediarss.MediaContent.prototype.setTexts",Q[t].bd);Q[t].fc=function(a){if(a[u]===m)a=new this.ae(a);this.media$text[q](a)};D("google.gdata.mediarss.MediaContent.prototype.addText",Q[t].fc);Q[t].of=function(){return this.media$thumbnail};D("google.gdata.mediarss.MediaContent.prototype.getThumbnails",Q[t].of);Q[t].cd=function(a){this.media$thumbnail=[];if(a)for(var d=0;d<a[r];d++)this.gc(a[d])};D("google.gdata.mediarss.MediaContent.prototype.setThumbnails",Q[t].cd);
Q[t].gc=function(a){if(a[u]===m)a=new this.be(a);this.media$thumbnail[q](a)};D("google.gdata.mediarss.MediaContent.prototype.addThumbnail",Q[t].gc);Q[t].fa=function(){return this.media$title};D("google.gdata.mediarss.MediaContent.prototype.getTitle",Q[t].fa);Q[t].K=function(a){if(a&&a[u]===m)a=new this.pa(a);this.media$title=a};D("google.gdata.mediarss.MediaContent.prototype.setTitle",Q[t].K);Q[t].o=function(){return this[B]};D("google.gdata.mediarss.MediaContent.prototype.getType",Q[t].o);
Q[t].l=function(a){o(this,a)};D("google.gdata.mediarss.MediaContent.prototype.setType",Q[t].l);Q[t].Ja=function(){return this.url};D("google.gdata.mediarss.MediaContent.prototype.getUrl",Q[t].Ja);Q[t].La=function(a){this.url=a};D("google.gdata.mediarss.MediaContent.prototype.setUrl",Q[t].La);Q[t].Ua=function(){return this[Ia]===undefined?undefined:k(this[Ia])};D("google.gdata.mediarss.MediaContent.prototype.getWidth",Q[t].Ua);Q[t].Ma=function(a){ma(this,a===undefined?undefined:i(a))};
D("google.gdata.mediarss.MediaContent.prototype.setWidth",Q[t].Ma);var R=function(a){if(!C(this.Ea))this.Ea=bj;if(!C(this.tk))this.tk=Q;if(!C(this.Ed))this.Ed=cj;if(!C(this.Gd))this.Gd=dj;if(!C(this.Id))this.Id=ej;if(!C(this.Md))this.Md=fj;if(!C(this.Od))this.Od=gj;if(!C(this.Td))this.Td=hj;if(!C(this.Vd))this.Vd=ij;if(!C(this.Xd))this.Xd=jj;if(!C(this.ae))this.ae=kj;if(!C(this.be))this.be=lj;if(!C(this.pa))this.pa=mj;if(a){this.ka(a.categories);this.Zh(a.contents);this.yc(a.copyright);this.Ac(a.credits);this.Cc(a.description);this.Gc(a[Ba]);this.Hc(a.keywords);
this.Mc(a.player);this.Nc(a.ratings);this.Pc(a.restrictions);this.bd(a.texts);this.cd(a.thumbnails);this.K(a[Da])}else{if(this.media$category)for(var d=this.media$category,e=0;e<d[r];e++)this.media$category[e]=E.util.mutateTo(d[e],this.Ea);else this.media$category=[];if(this.media$content){d=this.media$content;for(e=0;e<d[r];e++)this.media$content[e]=E.util.mutateTo(d[e],this.tk)}else this.media$content=[];this.media$copyright=E.util.mutateTo(this.media$copyright,this.Ed);if(this.media$credit){d=
this.media$credit;for(e=0;e<d[r];e++)this.media$credit[e]=E.util.mutateTo(d[e],this.Gd)}else this.media$credit=[];this.media$description=E.util.mutateTo(this.media$description,this.Id);this.media$hash=E.util.mutateTo(this.media$hash,this.Md);this.media$keywords=E.util.mutateTo(this.media$keywords,this.Od);this.media$player=E.util.mutateTo(this.media$player,this.Td);if(this.media$rating){d=this.media$rating;for(e=0;e<d[r];e++)this.media$rating[e]=E.util.mutateTo(d[e],this.Vd)}else this.media$rating=
[];if(this.media$restriction){d=this.media$restriction;for(e=0;e<d[r];e++)this.media$restriction[e]=E.util.mutateTo(d[e],this.Xd)}else this.media$restriction=[];if(this.media$text){d=this.media$text;for(e=0;e<d[r];e++)this.media$text[e]=E.util.mutateTo(d[e],this.ae)}else this.media$text=[];if(this.media$thumbnail){d=this.media$thumbnail;for(e=0;e<d[r];e++)this.media$thumbnail[e]=E.util.mutateTo(d[e],this.be)}else this.media$thumbnail=[];this.media$title=E.util.mutateTo(this.media$title,this.pa)}};
D("google.gdata.mediarss.MediaGroup",R);R[t].Ga=function(){return this.media$category};D("google.gdata.mediarss.MediaGroup.prototype.getCategories",R[t].Ga);R[t].ka=function(a){this.media$category=[];if(a)for(var d=0;d<a[r];d++)this.ia(a[d])};D("google.gdata.mediarss.MediaGroup.prototype.setCategories",R[t].ka);R[t].ia=function(a){if(a[u]===m)a=new this.Ea(a);this.media$category[q](a)};D("google.gdata.mediarss.MediaGroup.prototype.addCategory",R[t].ia);R[t].kn=function(){return this.media$content};
D("google.gdata.mediarss.MediaGroup.prototype.getContents",R[t].kn);R[t].Zh=function(a){this.media$content=[];if(a)for(var d=0;d<a[r];d++)this.Qg(a[d])};D("google.gdata.mediarss.MediaGroup.prototype.setContents",R[t].Zh);R[t].Qg=function(a){if(a[u]===m)a=new this.tk(a);this.media$content[q](a)};D("google.gdata.mediarss.MediaGroup.prototype.addContent",R[t].Qg);R[t].re=function(){return this.media$copyright};D("google.gdata.mediarss.MediaGroup.prototype.getCopyright",R[t].re);
R[t].yc=function(a){if(a&&a[u]===m)a=new this.Ed(a);this.media$copyright=a};D("google.gdata.mediarss.MediaGroup.prototype.setCopyright",R[t].yc);R[t].te=function(){return this.media$credit};D("google.gdata.mediarss.MediaGroup.prototype.getCredits",R[t].te);R[t].Ac=function(a){this.media$credit=[];if(a)for(var d=0;d<a[r];d++)this.Yb(a[d])};D("google.gdata.mediarss.MediaGroup.prototype.setCredits",R[t].Ac);R[t].Yb=function(a){if(a[u]===m)a=new this.Gd(a);this.media$credit[q](a)};
D("google.gdata.mediarss.MediaGroup.prototype.addCredit",R[t].Yb);R[t].xe=function(){return this.media$description};D("google.gdata.mediarss.MediaGroup.prototype.getDescription",R[t].xe);R[t].Cc=function(a){if(a&&a[u]===m)a=new this.Id(a);this.media$description=a};D("google.gdata.mediarss.MediaGroup.prototype.setDescription",R[t].Cc);R[t].De=function(){return this.media$hash};D("google.gdata.mediarss.MediaGroup.prototype.getHash",R[t].De);
R[t].Gc=function(a){if(a&&a[u]===m)a=new this.Md(a);this.media$hash=a};D("google.gdata.mediarss.MediaGroup.prototype.setHash",R[t].Gc);R[t].Fe=function(){return this.media$keywords};D("google.gdata.mediarss.MediaGroup.prototype.getKeywords",R[t].Fe);R[t].Hc=function(a){if(a&&a[u]===m)a=new this.Od(a);this.media$keywords=a};D("google.gdata.mediarss.MediaGroup.prototype.setKeywords",R[t].Hc);R[t].Ne=function(){return this.media$player};D("google.gdata.mediarss.MediaGroup.prototype.getPlayer",R[t].Ne);
R[t].Mc=function(a){if(a&&a[u]===m)a=new this.Td(a);this.media$player=a};D("google.gdata.mediarss.MediaGroup.prototype.setPlayer",R[t].Mc);R[t].Pe=function(){return this.media$rating};D("google.gdata.mediarss.MediaGroup.prototype.getRatings",R[t].Pe);R[t].Nc=function(a){this.media$rating=[];if(a)for(var d=0;d<a[r];d++)this.cc(a[d])};D("google.gdata.mediarss.MediaGroup.prototype.setRatings",R[t].Nc);R[t].cc=function(a){if(a[u]===m)a=new this.Vd(a);this.media$rating[q](a)};
D("google.gdata.mediarss.MediaGroup.prototype.addRating",R[t].cc);R[t].Ue=function(){return this.media$restriction};D("google.gdata.mediarss.MediaGroup.prototype.getRestrictions",R[t].Ue);R[t].Pc=function(a){this.media$restriction=[];if(a)for(var d=0;d<a[r];d++)this.ec(a[d])};D("google.gdata.mediarss.MediaGroup.prototype.setRestrictions",R[t].Pc);R[t].ec=function(a){if(a[u]===m)a=new this.Xd(a);this.media$restriction[q](a)};D("google.gdata.mediarss.MediaGroup.prototype.addRestriction",R[t].ec);
R[t].nf=function(){return this.media$text};D("google.gdata.mediarss.MediaGroup.prototype.getTexts",R[t].nf);R[t].bd=function(a){this.media$text=[];if(a)for(var d=0;d<a[r];d++)this.fc(a[d])};D("google.gdata.mediarss.MediaGroup.prototype.setTexts",R[t].bd);R[t].fc=function(a){if(a[u]===m)a=new this.ae(a);this.media$text[q](a)};D("google.gdata.mediarss.MediaGroup.prototype.addText",R[t].fc);R[t].of=function(){return this.media$thumbnail};D("google.gdata.mediarss.MediaGroup.prototype.getThumbnails",R[t].of);
R[t].cd=function(a){this.media$thumbnail=[];if(a)for(var d=0;d<a[r];d++)this.gc(a[d])};D("google.gdata.mediarss.MediaGroup.prototype.setThumbnails",R[t].cd);R[t].gc=function(a){if(a[u]===m)a=new this.be(a);this.media$thumbnail[q](a)};D("google.gdata.mediarss.MediaGroup.prototype.addThumbnail",R[t].gc);R[t].fa=function(){return this.media$title};D("google.gdata.mediarss.MediaGroup.prototype.getTitle",R[t].fa);R[t].K=function(a){if(a&&a[u]===m)a=new this.pa(a);this.media$title=a};
D("google.gdata.mediarss.MediaGroup.prototype.setTitle",R[t].K);

E.opensearch={};E.opensearch.namespace={};E.opensearch.namespace.OPENSEARCH="http://a9.com/-/spec/opensearchrss/1.0/";var dg=function(a){if(a)this.a(a[w]);else this.$t=this.$t};D("google.gdata.opensearch.ItemsPerPage",dg);dg[t].b=function(){return this.$t===undefined?undefined:k(this.$t)};D("google.gdata.opensearch.ItemsPerPage.prototype.getValue",dg[t].b);dg[t].a=function(a){this.$t=a===undefined?undefined:i(a)};D("google.gdata.opensearch.ItemsPerPage.prototype.setValue",dg[t].a);var eg=function(a){if(a)this.a(a[w]);else this.$t=this.$t};D("google.gdata.opensearch.StartIndex",eg);eg[t].b=function(){return this.$t===undefined?undefined:k(this.$t)};D("google.gdata.opensearch.StartIndex.prototype.getValue",eg[t].b);eg[t].a=function(a){this.$t=a===undefined?undefined:i(a)};D("google.gdata.opensearch.StartIndex.prototype.setValue",eg[t].a);var fg=function(a){if(a)this.a(a[w]);else this.$t=this.$t};D("google.gdata.opensearch.TotalResults",fg);fg[t].b=function(){return this.$t===undefined?undefined:k(this.$t)};D("google.gdata.opensearch.TotalResults.prototype.getValue",fg[t].b);fg[t].a=function(a){this.$t=a===undefined?undefined:i(a)};D("google.gdata.opensearch.TotalResults.prototype.setValue",fg[t].a);D("google.gdata.ItemsPerPage",dg);D("google.gdata.StartIndex",eg);D("google.gdata.TotalResults",fg);

function If(a,d){return a.title=d}E.atom={};E.atom.namespace={};E.atom.namespace.ATOM="http://www.w3.org/2005/Atom";E.atom.namespace.XML="http://www.w3.org/XML/1998/namespace";var Jf=function(a){if(a){xa(this,a[tb]);this.xml$lang=a.labelLang;pa(this,a[Qa]);this.term=a.term}else{xa(this,this[tb]);this.xml$lang=this.xml$lang;pa(this,this[Qa]);this.term=this.term}};D("google.gdata.atom.Category",Jf);Jf[t].I=function(){return this[tb]};D("google.gdata.atom.Category.prototype.getLabel",Jf[t].I);Jf[t].J=function(a){xa(this,a)};D("google.gdata.atom.Category.prototype.setLabel",Jf[t].J);Jf[t].Eo=function(){return this.xml$lang};
D("google.gdata.atom.Category.prototype.getLabelLang",Jf[t].Eo);Jf[t].Br=function(a){this.xml$lang=a};D("google.gdata.atom.Category.prototype.setLabelLang",Jf[t].Br);Jf[t].ya=function(){return this[Qa]};D("google.gdata.atom.Category.prototype.getScheme",Jf[t].ya);Jf[t].na=function(a){pa(this,a)};D("google.gdata.atom.Category.prototype.setScheme",Jf[t].na);Jf[t].zq=function(){return this.term};D("google.gdata.atom.Category.prototype.getTerm",Jf[t].zq);Jf[t].cs=function(a){this.term=a};
D("google.gdata.atom.Category.prototype.setTerm",Jf[t].cs);var Kf=function(a){this.$t=a?a[w]:this.$t};D("google.gdata.atom.Email",Kf);Kf[t].b=function(){return this.$t};D("google.gdata.atom.Email.prototype.getValue",Kf[t].b);Kf[t].a=function(a){this.$t=a};D("google.gdata.atom.Email.prototype.setValue",Kf[t].a);var Lf=function(a){if(a){this.$t=a[qb];this.uri=a.uri;this.version=a[Ea]}else{this.$t=this.$t;this.uri=this.uri;this.version=this[Ea]}};D("google.gdata.atom.Generator",Lf);Lf[t].u=function(){return this.$t};D("google.gdata.atom.Generator.prototype.getName",Lf[t].u);Lf[t].D=function(a){this.$t=a};D("google.gdata.atom.Generator.prototype.setName",Lf[t].D);Lf[t].Oa=function(){return this.uri};D("google.gdata.atom.Generator.prototype.getUri",Lf[t].Oa);Lf[t].sb=function(a){this.uri=a};
D("google.gdata.atom.Generator.prototype.setUri",Lf[t].sb);Lf[t].Oq=function(){return this[Ea]};D("google.gdata.atom.Generator.prototype.getVersion",Lf[t].Oq);Lf[t].hs=function(a){this.version=a};D("google.gdata.atom.Generator.prototype.setVersion",Lf[t].hs);var Mf=function(a){this.$t=a?a[w]:this.$t};D("google.gdata.atom.Id",Mf);Mf[t].b=function(){return this.$t};D("google.gdata.atom.Id.prototype.getValue",Mf[t].b);Mf[t].a=function(a){this.$t=a};D("google.gdata.atom.Id.prototype.setValue",Mf[t].a);var Nf=function(a){if(a){va(this,a[A]);this.hreflang=a.hrefLang;this.Ri(a[r]);this.rel=a.rel;If(this,a[Da]);this.xml$lang=a.titleLang;o(this,a[B])}else{va(this,this[A]);this.hreflang=this.hreflang;la(this,this[r]);this.rel=this.rel;If(this,this[Da]);this.xml$lang=this.xml$lang;o(this,this[B])}};D("google.gdata.atom.Link",Nf);Nf[t].T=function(){return this[A]};D("google.gdata.atom.Link.prototype.getHref",Nf[t].T);Nf[t].N=function(a){va(this,a)};D("google.gdata.atom.Link.prototype.setHref",Nf[t].N);
Nf[t].no=function(){return this.hreflang};D("google.gdata.atom.Link.prototype.getHrefLang",Nf[t].no);Nf[t].wr=function(a){this.hreflang=a};D("google.gdata.atom.Link.prototype.setHrefLang",Nf[t].wr);Nf[t].Go=function(){return this[r]===undefined?undefined:k(this[r])};D("google.gdata.atom.Link.prototype.getLength",Nf[t].Go);Nf[t].Ri=function(a){la(this,a===undefined?undefined:i(a))};D("google.gdata.atom.Link.prototype.setLength",Nf[t].Ri);Nf[t].q=function(){return this.rel};
D("google.gdata.atom.Link.prototype.getRel",Nf[t].q);Nf[t].p=function(a){this.rel=a};D("google.gdata.atom.Link.prototype.setRel",Nf[t].p);D("google.gdata.atom.Link.REL_ALTERNATE","alternate");D("google.gdata.atom.Link.REL_ENCLOSURE","enclosure");D("google.gdata.atom.Link.REL_ENTRY_EDIT","edit");D("google.gdata.atom.Link.REL_MEDIA_EDIT","edit-media");D("google.gdata.atom.Link.REL_NEXT","next");D("google.gdata.atom.Link.REL_PREVIOUS","previous");D("google.gdata.atom.Link.REL_RELATED","related");
D("google.gdata.atom.Link.REL_SELF","self");D("google.gdata.atom.Link.REL_VIA","via");Nf[t].fa=function(){return this[Da]};D("google.gdata.atom.Link.prototype.getTitle",Nf[t].fa);Nf[t].K=function(a){If(this,a)};D("google.gdata.atom.Link.prototype.setTitle",Nf[t].K);Nf[t].Dq=function(){return this.xml$lang};D("google.gdata.atom.Link.prototype.getTitleLang",Nf[t].Dq);Nf[t].ds=function(a){this.xml$lang=a};D("google.gdata.atom.Link.prototype.setTitleLang",Nf[t].ds);Nf[t].o=function(){return this[B]};
D("google.gdata.atom.Link.prototype.getType",Nf[t].o);Nf[t].l=function(a){o(this,a)};D("google.gdata.atom.Link.prototype.setType",Nf[t].l);D("google.gdata.atom.Link.TYPE_ATOM","application/atom+xml");D("google.gdata.atom.Link.TYPE_HTML","text/html");var Of=function(a){this.$t=a?a[w]:this.$t};D("google.gdata.atom.Logo",Of);Of[t].b=function(){return this.$t};D("google.gdata.atom.Logo.prototype.getValue",Of[t].b);Of[t].a=function(a){this.$t=a};D("google.gdata.atom.Logo.prototype.setValue",Of[t].a);var Pf=function(a){this.$t=a?a[w]:this.$t};D("google.gdata.atom.Name",Pf);Pf[t].b=function(){return this.$t};D("google.gdata.atom.Name.prototype.getValue",Pf[t].b);Pf[t].a=function(a){this.$t=a};D("google.gdata.atom.Name.prototype.setValue",Pf[t].a);var Qf=function(a){if(a)this.a(a[w]);else this.$t=this.$t};D("google.gdata.atom.Published",Qf);Qf[t].b=function(){return this.$t===undefined?undefined:G(this.$t)};D("google.gdata.atom.Published.prototype.getValue",Qf[t].b);Qf[t].a=function(a){this.$t=a===undefined?undefined:gf(a)};D("google.gdata.atom.Published.prototype.setValue",Qf[t].a);var Rf=function(a){if(a){this.xml$lang=a[Ga];this.$t=a.text;o(this,a[B]);this.src=a.uri}else{this.xml$lang=this.xml$lang;this.$t=this.$t;o(this,this[B]);this.src=this.src}};D("google.gdata.atom.Text",Rf);Rf[t].Ge=function(){return this.xml$lang};D("google.gdata.atom.Text.prototype.getLang",Rf[t].Ge);Rf[t].Gf=function(a){this.xml$lang=a};D("google.gdata.atom.Text.prototype.setLang",Rf[t].Gf);Rf[t].Aq=function(){return this.$t};D("google.gdata.atom.Text.prototype.getText",Rf[t].Aq);
Rf[t].Tj=function(a){this.$t=a};D("google.gdata.atom.Text.prototype.setText",Rf[t].Tj);Rf[t].o=function(){return this[B]};D("google.gdata.atom.Text.prototype.getType",Rf[t].o);Rf[t].l=function(a){o(this,a)};D("google.gdata.atom.Text.prototype.setType",Rf[t].l);Rf[t].Oa=function(){return this.src};D("google.gdata.atom.Text.prototype.getUri",Rf[t].Oa);Rf[t].sb=function(a){this.src=a};D("google.gdata.atom.Text.prototype.setUri",Rf[t].sb);var Sf=function(a,d){var e=new Rf;e.Tj(a);e.l(d||"text");return e};
D("google.gdata.atom.Text.create",Sf);var Tf=function(a){if(a)this.a(a[w]);else this.$t=this.$t};D("google.gdata.atom.Updated",Tf);Tf[t].b=function(){return this.$t===undefined?undefined:G(this.$t)};D("google.gdata.atom.Updated.prototype.getValue",Tf[t].b);Tf[t].a=function(a){this.$t=a===undefined?undefined:gf(a)};D("google.gdata.atom.Updated.prototype.setValue",Tf[t].a);var Uf=function(a){this.$t=a?a[w]:this.$t};D("google.gdata.atom.Uri",Uf);Uf[t].b=function(){return this.$t};D("google.gdata.atom.Uri.prototype.getValue",Uf[t].b);Uf[t].a=function(a){this.$t=a};D("google.gdata.atom.Uri.prototype.setValue",Uf[t].a);var Vf=function(a){if(!C(this.Dk))this.Dk=Kf;if(!C(this.dl))this.dl=Pf;if(!C(this.$l))this.$l=Uf;if(a){this.ud(a.email);this.D(a[qb]);this.xml$lang=a.nameLang;this.sb(a.uri)}else{this.email=E.util.mutateTo(this.email,this.Dk);wa(this,E.util.mutateTo(this[qb],this.dl));this.xml$lang=this.xml$lang;this.uri=E.util.mutateTo(this.uri,this.$l)}};D("google.gdata.atom.Person",Vf);Vf[t].ye=function(){return this.email};D("google.gdata.atom.Person.prototype.getEmail",Vf[t].ye);
Vf[t].ud=function(a){if(a&&a[u]===m)a=new this.Dk(a);this.email=a};D("google.gdata.atom.Person.prototype.setEmail",Vf[t].ud);Vf[t].u=function(){return this[qb]};D("google.gdata.atom.Person.prototype.getName",Vf[t].u);Vf[t].D=function(a){if(a&&a[u]===m)a=new this.dl(a);wa(this,a)};D("google.gdata.atom.Person.prototype.setName",Vf[t].D);Vf[t].$o=function(){return this.xml$lang};D("google.gdata.atom.Person.prototype.getNameLang",Vf[t].$o);Vf[t].Kr=function(a){this.xml$lang=a};
D("google.gdata.atom.Person.prototype.setNameLang",Vf[t].Kr);Vf[t].Oa=function(){return this.uri};D("google.gdata.atom.Person.prototype.getUri",Vf[t].Oa);Vf[t].sb=function(a){if(a&&a[u]===m)a=new this.$l(a);this.uri=a};D("google.gdata.atom.Person.prototype.setUri",Vf[t].sb);var H=function(a){if(!C(this.Cd))this.Cd=Vf;if(!C(this.Ea))this.Ea=Jf;if(!C(this.ig))this.ig=Rf;if(!C(this.Dd))this.Dd=Vf;if(!C(this.Nd))this.Nd=Mf;if(!C(this.n))this.n=Nf;if(!C(this.vl))this.vl=Qf;if(!C(this.Yd))this.Yd=Rf;if(!C(this.Ol))this.Ol=Rf;if(!C(this.pa))this.pa=Rf;if(!C(this.ge))this.ge=Tf;if(a){this.vc(a.authors);this.ka(a.categories);this.r(a[Oa]);this.xc(a.contributors);this.Ba(a.id);this.Ic(a.links);this.tj(a.published);this.Yc(a.rights);this.Oj(a.summary);this.K(a[Da]);this.db(a.updated)}else{if(this.author)for(var d=
this.author,e=0;e<d[r];e++)this.author[e]=E.util.mutateTo(d[e],this.Cd);else this.author=[];if(this.category){d=this.category;for(e=0;e<d[r];e++)this.category[e]=E.util.mutateTo(d[e],this.Ea)}else this.category=[];na(this,E.util.mutateTo(this[Oa],this.ig));if(this.contributor){d=this.contributor;for(e=0;e<d[r];e++)this.contributor[e]=E.util.mutateTo(d[e],this.Dd)}else this.contributor=[];this.id=E.util.mutateTo(this.id,this.Nd);if(this.link){d=this.link;for(e=0;e<d[r];e++)this.link[e]=E.util.mutateTo(d[e],
this.n)}else this.link=[];this.published=E.util.mutateTo(this.published,this.vl);this.rights=E.util.mutateTo(this.rights,this.Yd);this.summary=E.util.mutateTo(this.summary,this.Ol);If(this,E.util.mutateTo(this[Da],this.pa));this.updated=E.util.mutateTo(this.updated,this.ge)}};D("google.gdata.atom.Entry",H);H[t].jd=E.atom.namespace.ATOM;D("google.gdata.atom.Entry.prototype.xmlns",H[t].jd);H[t].Rf=E.atom.namespace.XML;D("google.gdata.atom.Entry.prototype.xmlns$xml",H[t].Rf);H[t].me=function(){return this.author};
D("google.gdata.atom.Entry.prototype.getAuthors",H[t].me);H[t].vc=function(a){this.author=[];if(a)for(var d=0;d<a[r];d++)this.Wb(a[d])};D("google.gdata.atom.Entry.prototype.setAuthors",H[t].vc);H[t].Wb=function(a){if(a[u]===m)a=new this.Cd(a);this.author[q](a)};D("google.gdata.atom.Entry.prototype.addAuthor",H[t].Wb);H[t].Ga=function(){return this.category};D("google.gdata.atom.Entry.prototype.getCategories",H[t].Ga);H[t].ka=function(a){this.category=[];if(a)for(var d=0;d<a[r];d++)this.ia(a[d])};
D("google.gdata.atom.Entry.prototype.setCategories",H[t].ka);H[t].ia=function(a){if(a[u]===m)a=new this.Ea(a);this.category[q](a)};D("google.gdata.atom.Entry.prototype.addCategory",H[t].ia);H[t].s=function(){return this[Oa]};D("google.gdata.atom.Entry.prototype.getContent",H[t].s);H[t].r=function(a){if(a&&a[u]===m)a=new this.ig(a);na(this,a)};D("google.gdata.atom.Entry.prototype.setContent",H[t].r);H[t].qe=function(){return this.contributor};D("google.gdata.atom.Entry.prototype.getContributors",H[t].qe);
H[t].xc=function(a){this.contributor=[];if(a)for(var d=0;d<a[r];d++)this.Xb(a[d])};D("google.gdata.atom.Entry.prototype.setContributors",H[t].xc);H[t].Xb=function(a){if(a[u]===m)a=new this.Dd(a);this.contributor[q](a)};D("google.gdata.atom.Entry.prototype.addContributor",H[t].Xb);H[t].Ia=function(){return this.id};D("google.gdata.atom.Entry.prototype.getId",H[t].Ia);H[t].Ba=function(a){if(a&&a[u]===m)a=new this.Nd(a);this.id=a};D("google.gdata.atom.Entry.prototype.setId",H[t].Ba);H[t].He=function(){return this.link};
D("google.gdata.atom.Entry.prototype.getLinks",H[t].He);H[t].Ic=function(a){this.link=[];if(a)for(var d=0;d<a[r];d++)this.Zb(a[d])};D("google.gdata.atom.Entry.prototype.setLinks",H[t].Ic);H[t].Zb=function(a){if(a[u]===m)a=new this.n(a);this.link[q](a)};D("google.gdata.atom.Entry.prototype.addLink",H[t].Zb);H[t].Ip=function(){return this.published};D("google.gdata.atom.Entry.prototype.getPublished",H[t].Ip);H[t].tj=function(a){if(a&&a[u]===m)a=new this.vl(a);this.published=a};
D("google.gdata.atom.Entry.prototype.setPublished",H[t].tj);H[t].cf=function(){return this.rights};D("google.gdata.atom.Entry.prototype.getRights",H[t].cf);H[t].Yc=function(a){if(a&&a[u]===m)a=new this.Yd(a);this.rights=a};D("google.gdata.atom.Entry.prototype.setRights",H[t].Yc);H[t].tq=function(){return this.summary};D("google.gdata.atom.Entry.prototype.getSummary",H[t].tq);H[t].Oj=function(a){if(a&&a[u]===m)a=new this.Ol(a);this.summary=a};D("google.gdata.atom.Entry.prototype.setSummary",H[t].Oj);
H[t].fa=function(){return this[Da]};D("google.gdata.atom.Entry.prototype.getTitle",H[t].fa);H[t].K=function(a){if(a&&a[u]===m)a=new this.pa(a);If(this,a)};D("google.gdata.atom.Entry.prototype.setTitle",H[t].K);H[t].Gb=function(){return this.updated};D("google.gdata.atom.Entry.prototype.getUpdated",H[t].Gb);H[t].db=function(a){if(a&&a[u]===m)a=new this.ge(a);this.updated=a};D("google.gdata.atom.Entry.prototype.setUpdated",H[t].db);var I=function(a){if(!C(this.Cd))this.Cd=Vf;if(!C(this.Ea))this.Ea=Jf;if(!C(this.Dd))this.Dd=Vf;if(!C(this.m))this.m=H;if(!C(this.Lk))this.Lk=Lf;if(!C(this.Nd))this.Nd=Mf;if(!C(this.n))this.n=Nf;if(!C(this.al))this.al=Of;if(!C(this.Yd))this.Yd=Rf;if(!C(this.Nl))this.Nl=Rf;if(!C(this.pa))this.pa=Rf;if(!C(this.ge))this.ge=Tf;if(a){this.vc(a.authors);this.xml$base=a.base;this.ka(a.categories);this.xc(a.contributors);this.oi(a.entries);this.Ai(a.generator);this.Ba(a.id);this.Ic(a.links);this.Ui(a.logo);
this.Yc(a.rights);this.Hg(a.subtitle);this.K(a[Da]);this.db(a.updated)}else{if(this.author)for(var d=this.author,e=0;e<d[r];e++)this.author[e]=E.util.mutateTo(d[e],this.Cd);else this.author=[];this.xml$base=this.xml$base;if(this.category){d=this.category;for(e=0;e<d[r];e++)this.category[e]=E.util.mutateTo(d[e],this.Ea)}else this.category=[];if(this.contributor){d=this.contributor;for(e=0;e<d[r];e++)this.contributor[e]=E.util.mutateTo(d[e],this.Dd)}else this.contributor=[];if(this.entry){d=this.entry;
for(e=0;e<d[r];e++)this.entry[e]=E.util.mutateTo(d[e],this.m)}else this.entry=[];this.generator=E.util.mutateTo(this.generator,this.Lk);this.id=E.util.mutateTo(this.id,this.Nd);if(this.link){d=this.link;for(e=0;e<d[r];e++)this.link[e]=E.util.mutateTo(d[e],this.n)}else this.link=[];this.logo=E.util.mutateTo(this.logo,this.al);this.rights=E.util.mutateTo(this.rights,this.Yd);this.subtitle=E.util.mutateTo(this.subtitle,this.Nl);If(this,E.util.mutateTo(this[Da],this.pa));this.updated=E.util.mutateTo(this.updated,
this.ge)}};D("google.gdata.atom.Feed",I);I[t].jd=E.atom.namespace.ATOM;D("google.gdata.atom.Feed.prototype.xmlns",I[t].jd);I[t].Rf=E.atom.namespace.XML;D("google.gdata.atom.Feed.prototype.xmlns$xml",I[t].Rf);I[t].me=function(){return this.author};D("google.gdata.atom.Feed.prototype.getAuthors",I[t].me);I[t].vc=function(a){this.author=[];if(a)for(var d=0;d<a[r];d++)this.Wb(a[d])};D("google.gdata.atom.Feed.prototype.setAuthors",I[t].vc);I[t].Wb=function(a){if(a[u]===m)a=new this.Cd(a);this.author[q](a)};
D("google.gdata.atom.Feed.prototype.addAuthor",I[t].Wb);I[t].Om=function(){return this.xml$base};D("google.gdata.atom.Feed.prototype.getBase",I[t].Om);I[t].ir=function(a){this.xml$base=a};D("google.gdata.atom.Feed.prototype.setBase",I[t].ir);I[t].Ga=function(){return this.category};D("google.gdata.atom.Feed.prototype.getCategories",I[t].Ga);I[t].ka=function(a){this.category=[];if(a)for(var d=0;d<a[r];d++)this.ia(a[d])};D("google.gdata.atom.Feed.prototype.setCategories",I[t].ka);
I[t].ia=function(a){if(a[u]===m)a=new this.Ea(a);this.category[q](a)};D("google.gdata.atom.Feed.prototype.addCategory",I[t].ia);I[t].qe=function(){return this.contributor};D("google.gdata.atom.Feed.prototype.getContributors",I[t].qe);I[t].xc=function(a){this.contributor=[];if(a)for(var d=0;d<a[r];d++)this.Xb(a[d])};D("google.gdata.atom.Feed.prototype.setContributors",I[t].xc);I[t].Xb=function(a){if(a[u]===m)a=new this.Dd(a);this.contributor[q](a)};
D("google.gdata.atom.Feed.prototype.addContributor",I[t].Xb);I[t].Fn=function(){return this.entry};D("google.gdata.atom.Feed.prototype.getEntries",I[t].Fn);I[t].oi=function(a){this.entry=[];if(a)for(var d=0;d<a[r];d++)this.Vg(a[d])};D("google.gdata.atom.Feed.prototype.setEntries",I[t].oi);I[t].Vg=function(a){if(a[u]===m)a=new this.m(a);this.entry[q](a)};D("google.gdata.atom.Feed.prototype.addEntry",I[t].Vg);I[t].$n=function(){return this.generator};
D("google.gdata.atom.Feed.prototype.getGenerator",I[t].$n);I[t].Ai=function(a){if(a&&a[u]===m)a=new this.Lk(a);this.generator=a};D("google.gdata.atom.Feed.prototype.setGenerator",I[t].Ai);I[t].Ia=function(){return this.id};D("google.gdata.atom.Feed.prototype.getId",I[t].Ia);I[t].Ba=function(a){if(a&&a[u]===m)a=new this.Nd(a);this.id=a};D("google.gdata.atom.Feed.prototype.setId",I[t].Ba);I[t].He=function(){return this.link};D("google.gdata.atom.Feed.prototype.getLinks",I[t].He);
I[t].Ic=function(a){this.link=[];if(a)for(var d=0;d<a[r];d++)this.Zb(a[d])};D("google.gdata.atom.Feed.prototype.setLinks",I[t].Ic);I[t].Zb=function(a){if(a[u]===m)a=new this.n(a);this.link[q](a)};D("google.gdata.atom.Feed.prototype.addLink",I[t].Zb);I[t].Ko=function(){return this.logo};D("google.gdata.atom.Feed.prototype.getLogo",I[t].Ko);I[t].Ui=function(a){if(a&&a[u]===m)a=new this.al(a);this.logo=a};D("google.gdata.atom.Feed.prototype.setLogo",I[t].Ui);I[t].cf=function(){return this.rights};
D("google.gdata.atom.Feed.prototype.getRights",I[t].cf);I[t].Yc=function(a){if(a&&a[u]===m)a=new this.Yd(a);this.rights=a};D("google.gdata.atom.Feed.prototype.setRights",I[t].Yc);I[t].zh=function(){return this.subtitle};D("google.gdata.atom.Feed.prototype.getSubtitle",I[t].zh);I[t].Hg=function(a){if(a&&a[u]===m)a=new this.Nl(a);this.subtitle=a};D("google.gdata.atom.Feed.prototype.setSubtitle",I[t].Hg);I[t].fa=function(){return this[Da]};D("google.gdata.atom.Feed.prototype.getTitle",I[t].fa);
I[t].K=function(a){if(a&&a[u]===m)a=new this.pa(a);If(this,a)};D("google.gdata.atom.Feed.prototype.setTitle",I[t].K);I[t].Gb=function(){return this.updated};D("google.gdata.atom.Feed.prototype.getUpdated",I[t].Gb);I[t].db=function(a){if(a&&a[u]===m)a=new this.ge(a);this.updated=a};D("google.gdata.atom.Feed.prototype.setUpdated",I[t].db);D("google.gdata.Category",Jf);D("google.gdata.Generator",Lf);D("google.gdata.Id",Mf);D("google.gdata.Person",Vf);D("google.gdata.Published",Qf);D("google.gdata.Text",Rf);D("google.gdata.Updated",Tf);D("google.gdata.Uri",Uf);I[t].rq=function(){return this.zh()};D("google.gdata.atom.Feed.prototype.getSubTitle",I[t].rq);I[t].bs=function(a){return this.Hg(a)};D("google.gdata.atom.Feed.prototype.setSubTitle",I[t].bs);H[t].ne=function(){return Jf};
D("google.gdata.atom.Entry.prototype.getCategoryClass",H[t].ne);H[t].H=function(){return Nf};D("google.gdata.atom.Entry.prototype.getLinkClass",H[t].H);I[t].ne=function(){return Jf};D("google.gdata.atom.Feed.prototype.getCategoryClass",I[t].ne);I[t].da=function(){return H};D("google.gdata.atom.Feed.prototype.getEntryClass",I[t].da);I[t].H=function(){return Nf};D("google.gdata.atom.Feed.prototype.getLinkClass",I[t].H);

E.app={};E.app.namespace={};E.app.namespace.APP="http://purl.org/atom/app#";var Wf=function(a){this.$t=a?a[w]:this.$t};D("google.gdata.app.Accept",Wf);Wf[t].b=function(){return this.$t};D("google.gdata.app.Accept.prototype.getValue",Wf[t].b);Wf[t].a=function(a){this.$t=a};D("google.gdata.app.Accept.prototype.setValue",Wf[t].a);var Xf=function(a){if(!C(this.Ea))this.Ea=Jf;if(a){this.ka(a.categories);this.fixed=a.fixed;va(this,a[A]);pa(this,a[Qa])}else{if(this.category)for(var d=this.category,e=0;e<d[r];e++)this.category[e]=E.util.mutateTo(d[e],this.Ea);else this.category=[];this.fixed=this.fixed;va(this,this[A]);pa(this,this[Qa])}};D("google.gdata.app.Categories",Xf);Xf[t].Ga=function(){return this.category};D("google.gdata.app.Categories.prototype.getCategories",Xf[t].Ga);
Xf[t].ka=function(a){this.category=[];if(a)for(var d=0;d<a[r];d++)this.ia(a[d])};D("google.gdata.app.Categories.prototype.setCategories",Xf[t].ka);Xf[t].ia=function(a){if(a[u]===m)a=new this.Ea(a);this.category[q](a)};D("google.gdata.app.Categories.prototype.addCategory",Xf[t].ia);Xf[t].Sn=function(){return this.fixed};D("google.gdata.app.Categories.prototype.getFixed",Xf[t].Sn);Xf[t].qr=function(a){this.fixed=a};D("google.gdata.app.Categories.prototype.setFixed",Xf[t].qr);
D("google.gdata.app.Categories.FIXED_NO","no");D("google.gdata.app.Categories.FIXED_YES","yes");Xf[t].T=function(){return this[A]};D("google.gdata.app.Categories.prototype.getHref",Xf[t].T);Xf[t].N=function(a){va(this,a)};D("google.gdata.app.Categories.prototype.setHref",Xf[t].N);Xf[t].ya=function(){return this[Qa]};D("google.gdata.app.Categories.prototype.getScheme",Xf[t].ya);Xf[t].na=function(a){pa(this,a)};D("google.gdata.app.Categories.prototype.setScheme",Xf[t].na);var Yf=function(a){if(!C(this.fk))this.fk=Wf;if(!C(this.ok))this.ok=Xf;if(!C(this.pa))this.pa=Rf;if(a){this.Hh(a.accepts);this.Sh(a.categorieses);va(this,a[A]);this.K(a[Da])}else{if(this.app$accept)for(var d=this.app$accept,e=0;e<d[r];e++)this.app$accept[e]=E.util.mutateTo(d[e],this.fk);else this.app$accept=[];if(this.app$categories){d=this.app$categories;for(e=0;e<d[r];e++)this.app$categories[e]=E.util.mutateTo(d[e],this.ok)}else this.app$categories=[];va(this,this[A]);If(this,E.util.mutateTo(this[Da],
this.pa))}};D("google.gdata.app.Collection",Yf);Yf[t].wm=function(){return this.app$accept};D("google.gdata.app.Collection.prototype.getAccepts",Yf[t].wm);Yf[t].Hh=function(a){this.app$accept=[];if(a)for(var d=0;d<a[r];d++)this.Mg(a[d])};D("google.gdata.app.Collection.prototype.setAccepts",Yf[t].Hh);Yf[t].Mg=function(a){if(a[u]===m)a=new this.fk(a);this.app$accept[q](a)};D("google.gdata.app.Collection.prototype.addAccept",Yf[t].Mg);Yf[t].Vm=function(){return this.app$categories};
D("google.gdata.app.Collection.prototype.getCategorieses",Yf[t].Vm);Yf[t].Sh=function(a){this.app$categories=[];if(a)for(var d=0;d<a[r];d++)this.Og(a[d])};D("google.gdata.app.Collection.prototype.setCategorieses",Yf[t].Sh);Yf[t].Og=function(a){if(a[u]===m)a=new this.ok(a);this.app$categories[q](a)};D("google.gdata.app.Collection.prototype.addCategories",Yf[t].Og);Yf[t].T=function(){return this[A]};D("google.gdata.app.Collection.prototype.getHref",Yf[t].T);Yf[t].N=function(a){va(this,a)};
D("google.gdata.app.Collection.prototype.setHref",Yf[t].N);Yf[t].fa=function(){return this[Da]};D("google.gdata.app.Collection.prototype.getTitle",Yf[t].fa);Yf[t].K=function(a){if(a&&a[u]===m)a=new this.pa(a);If(this,a)};D("google.gdata.app.Collection.prototype.setTitle",Yf[t].K);var Zf=function(a){this.$t=a?a[w]:this.$t};D("google.gdata.app.Draft",Zf);Zf[t].b=function(){return this.$t};D("google.gdata.app.Draft.prototype.getValue",Zf[t].b);Zf[t].a=function(a){this.$t=a};D("google.gdata.app.Draft.prototype.setValue",Zf[t].a);D("google.gdata.app.Draft.VALUE_NO","no");D("google.gdata.app.Draft.VALUE_YES","yes");var $f=function(a){if(a)this.a(a[w]);else this.$t=this.$t};D("google.gdata.app.Edited",$f);$f[t].b=function(){return this.$t===undefined?undefined:G(this.$t)};D("google.gdata.app.Edited.prototype.getValue",$f[t].b);$f[t].a=function(a){this.$t=a===undefined?undefined:gf(a)};D("google.gdata.app.Edited.prototype.setValue",$f[t].a);var ag=function(a){if(!C(this.qk))this.qk=Yf;if(!C(this.pa))this.pa=Rf;if(a){this.Vh(a.collections);this.K(a[Da])}else{if(this.app$collection)for(var d=this.app$collection,e=0;e<d[r];e++)this.app$collection[e]=E.util.mutateTo(d[e],this.qk);else this.app$collection=[];If(this,E.util.mutateTo(this[Da],this.pa))}};D("google.gdata.app.Workspace",ag);ag[t].Zm=function(){return this.app$collection};D("google.gdata.app.Workspace.prototype.getCollections",ag[t].Zm);
ag[t].Vh=function(a){this.app$collection=[];if(a)for(var d=0;d<a[r];d++)this.Pg(a[d])};D("google.gdata.app.Workspace.prototype.setCollections",ag[t].Vh);ag[t].Pg=function(a){if(a[u]===m)a=new this.qk(a);this.app$collection[q](a)};D("google.gdata.app.Workspace.prototype.addCollection",ag[t].Pg);ag[t].fa=function(){return this[Da]};D("google.gdata.app.Workspace.prototype.getTitle",ag[t].fa);ag[t].K=function(a){if(a&&a[u]===m)a=new this.pa(a);If(this,a)};
D("google.gdata.app.Workspace.prototype.setTitle",ag[t].K);var bg=function(a){if(!C(this.Ak))this.Ak=Zf;if(a)this.ii(a.draft);else this.app$draft=E.util.mutateTo(this.app$draft,this.Ak)};D("google.gdata.app.Control",bg);bg[t].xn=function(){return this.app$draft};D("google.gdata.app.Control.prototype.getDraft",bg[t].xn);bg[t].ii=function(a){if(a&&a[u]===m)a=new this.Ak(a);this.app$draft=a};D("google.gdata.app.Control.prototype.setDraft",bg[t].ii);var cg=function(a){if(!C(this.fm))this.fm=ag;if(a)this.ek(a.workspaces);else if(this.app$workspace)for(var d=this.app$workspace,e=0;e<d[r];e++)this.app$workspace[e]=E.util.mutateTo(d[e],this.fm);else this.app$workspace=[]};D("google.gdata.app.ServiceDocument",cg);cg[t].Sq=function(){return this.app$workspace};D("google.gdata.app.ServiceDocument.prototype.getWorkspaces",cg[t].Sq);cg[t].ek=function(a){this.app$workspace=[];if(a)for(var d=0;d<a[r];d++)this.kh(a[d])};
D("google.gdata.app.ServiceDocument.prototype.setWorkspaces",cg[t].ek);cg[t].kh=function(a){if(a[u]===m)a=new this.fm(a);this.app$workspace[q](a)};D("google.gdata.app.ServiceDocument.prototype.addWorkspace",cg[t].kh);D("google.gdata.Control",bg);D("google.gdata.Draft",Zf);D("google.gdata.Edited",$f);

function gg(a,d){return a.readOnly=d}var hg="$service_",ig="readOnly";E.namespace={};E.namespace.GD="http://schemas.google.com/g/2005";var jg=function(a){this.$t=a?a[w]:this.$t};D("google.gdata.Agent",jg);jg[t].b=function(){return this.$t};D("google.gdata.Agent.prototype.getValue",jg[t].b);jg[t].a=function(a){this.$t=a};D("google.gdata.Agent.prototype.setValue",jg[t].a);var kg=function(a){n(this,a?a[w]:this[w])};D("google.gdata.AttendeeStatus",kg);kg[t].b=function(){return this[w]};D("google.gdata.AttendeeStatus.prototype.getValue",kg[t].b);kg[t].a=function(a){n(this,a)};D("google.gdata.AttendeeStatus.prototype.setValue",kg[t].a);var lg=E.namespace.GD+"#event.accepted";D("google.gdata.AttendeeStatus.VALUE_ACCEPTED",lg);var mg=E.namespace.GD+"#event.declined";D("google.gdata.AttendeeStatus.VALUE_DECLINED",mg);var ng=E.namespace.GD+"#event.invited";
D("google.gdata.AttendeeStatus.VALUE_INVITED",ng);var og=E.namespace.GD+"#event.tentative";D("google.gdata.AttendeeStatus.VALUE_TENTATIVE",og);var pg=function(a){n(this,a?a[w]:this[w])};D("google.gdata.AttendeeType",pg);pg[t].b=function(){return this[w]};D("google.gdata.AttendeeType.prototype.getValue",pg[t].b);pg[t].a=function(a){n(this,a)};D("google.gdata.AttendeeType.prototype.setValue",pg[t].a);var qg=E.namespace.GD+"#event.optional";D("google.gdata.AttendeeType.VALUE_OPTIONAL",qg);var rg=E.namespace.GD+"#event.required";D("google.gdata.AttendeeType.VALUE_REQUIRED",rg);var sg=function(a){this.$t=a?a[w]:this.$t};D("google.gdata.City",sg);sg[t].b=function(){return this.$t};D("google.gdata.City.prototype.getValue",sg[t].b);sg[t].a=function(a){this.$t=a};D("google.gdata.City.prototype.setValue",sg[t].a);var tg=function(a){if(a){this.code=a.code;this.$t=a[w]}else{this.code=this.code;this.$t=this.$t}};D("google.gdata.Country",tg);tg[t].Ym=function(){return this.code};D("google.gdata.Country.prototype.getCode",tg[t].Ym);tg[t].jr=function(a){this.code=a};D("google.gdata.Country.prototype.setCode",tg[t].jr);tg[t].b=function(){return this.$t};D("google.gdata.Country.prototype.getValue",tg[t].b);tg[t].a=function(a){this.$t=a};D("google.gdata.Country.prototype.setValue",tg[t].a);var ug=function(a){if(a){wa(this,a[qb]);o(this,a[B]);this.unit=a.unit;this.$t=a[w]}else{wa(this,this[qb]);o(this,this[B]);this.unit=this.unit;this.$t=this.$t}};D("google.gdata.CustomProperty",ug);ug[t].u=function(){return this[qb]};D("google.gdata.CustomProperty.prototype.getName",ug[t].u);ug[t].D=function(a){wa(this,a)};D("google.gdata.CustomProperty.prototype.setName",ug[t].D);ug[t].o=function(){return this[B]};D("google.gdata.CustomProperty.prototype.getType",ug[t].o);
ug[t].l=function(a){o(this,a)};D("google.gdata.CustomProperty.prototype.setType",ug[t].l);ug[t].Jq=function(){return this.unit};D("google.gdata.CustomProperty.prototype.getUnit",ug[t].Jq);ug[t].es=function(a){this.unit=a};D("google.gdata.CustomProperty.prototype.setUnit",ug[t].es);ug[t].b=function(){return this.$t};D("google.gdata.CustomProperty.prototype.getValue",ug[t].b);ug[t].a=function(a){this.$t=a};D("google.gdata.CustomProperty.prototype.setValue",ug[t].a);var vg=function(){};D("google.gdata.Deleted",vg);var wg=function(a){if(a){this.address=a.address;xa(this,a[tb]);this.aa(a.primary);this.rel=a.rel}else{this.address=this.address;xa(this,this[tb]);this.primary=this.primary;this.rel=this.rel}};D("google.gdata.Email",wg);wg[t].ke=function(){return this.address};D("google.gdata.Email.prototype.getAddress",wg[t].ke);wg[t].Bf=function(a){this.address=a};D("google.gdata.Email.prototype.setAddress",wg[t].Bf);wg[t].I=function(){return this[tb]};D("google.gdata.Email.prototype.getLabel",wg[t].I);
wg[t].J=function(a){xa(this,a)};D("google.gdata.Email.prototype.setLabel",wg[t].J);wg[t].va=function(){return this.primary===undefined?undefined:this.primary==="true"};D("google.gdata.Email.prototype.getPrimary",wg[t].va);wg[t].aa=function(a){this.primary=a===undefined?undefined:i(a)};D("google.gdata.Email.prototype.setPrimary",wg[t].aa);wg[t].q=function(){return this.rel};D("google.gdata.Email.prototype.getRel",wg[t].q);wg[t].p=function(a){this.rel=a};D("google.gdata.Email.prototype.setRel",wg[t].p);
var xg=E.namespace.GD+"#home";D("google.gdata.Email.REL_HOME",xg);var yg=E.namespace.GD+"#other";D("google.gdata.Email.REL_OTHER",yg);var zg=E.namespace.GD+"#work";D("google.gdata.Email.REL_WORK",zg);var J=function(a){if(!C(this.jg))this.jg=bg;if(!C(this.Bk))this.Bk=$f;H[z](this,a);if(a){this.$h(a.control);this.ki(a.edited)}else{this.app$control=E.util.mutateTo(this.app$control,this.jg);this.app$edited=E.util.mutateTo(this.app$edited,this.Bk)}};D("google.gdata.Entry",J);J.e(H);J[t].Nf=E.app.namespace.APP;D("google.gdata.Entry.prototype.xmlns$app",J[t].Nf);J[t].ln=function(){return this.app$control};D("google.gdata.Entry.prototype.getControl",J[t].ln);
J[t].$h=function(a){if(a&&a[u]===m)a=new this.jg(a);this.app$control=a};D("google.gdata.Entry.prototype.setControl",J[t].$h);J[t].zn=function(){return this.app$edited};D("google.gdata.Entry.prototype.getEdited",J[t].zn);J[t].ki=function(a){if(a&&a[u]===m)a=new this.Bk(a);this.app$edited=a};D("google.gdata.Entry.prototype.setEdited",J[t].ki);J[t].wg=function(){return this.g("edit","application/atom+xml")};D("google.gdata.Entry.prototype.getEditLink",J[t].wg);
J[t].oc=function(){return this.g("self","application/atom+xml")};D("google.gdata.Entry.prototype.getSelfLink",J[t].oc);J[t].g=function(a,d){var e=E.util.vh(this.link,a,d);return e===undefined?undefined:this.link[e]};D("google.gdata.Entry.prototype.getLink",J[t].g);
J[t].ef=function(a,d){if(!this[hg])return E.util.handleError(Error("entry is not associated with a GData service"),d);var e=this.oc();if(!e||!e[A])return E.util.handleError(Error("entry has no self link"),d);var h=e[A];return this[hg].O(h,a,d,this[u])};D("google.gdata.Entry.prototype.getSelf",J[t].ef);
J[t].Ad=function(a,d){if(!this[hg])return E.util.handleError(Error("entry is not associated with a GData service"),d);var e=this.wg();if(!e||!e[A])return E.util.handleError(Error("entry has no edit link"),d);var h=e[A];return this[hg].Ad(h,this,a,d)};D("google.gdata.Entry.prototype.updateEntry",J[t].Ad);
J[t].kd=function(a,d){if(!this[hg])return E.util.handleError(Error("entry is not associated with a GData service"),d);var e=this.wg();if(!e||!e[A])return E.util.handleError(Error("entry has no edit link"),d);var h=e[A];this[hg].kd(h,a,d)};D("google.gdata.Entry.prototype.deleteEntry",J[t].kd);var Ag=function(a){if(!C(this.Jd))this.Jd=J;if(a){this.pi(a.entry);va(this,a[A]);this.Nb(a[ig]);this.rel=a.rel}else{this.entry=E.util.mutateTo(this.entry,this.Jd);va(this,this[A]);gg(this,this[ig]);this.rel=this.rel}};D("google.gdata.EntryLink",Ag);Ag[t].O=function(){return this.entry};D("google.gdata.EntryLink.prototype.getEntry",Ag[t].O);Ag[t].pi=function(a){if(a&&a[u]===m)a=new this.Jd(a);this.entry=a};D("google.gdata.EntryLink.prototype.setEntry",Ag[t].pi);Ag[t].T=function(){return this[A]};
D("google.gdata.EntryLink.prototype.getHref",Ag[t].T);Ag[t].N=function(a){va(this,a)};D("google.gdata.EntryLink.prototype.setHref",Ag[t].N);Ag[t].Qe=function(){return this[ig]===undefined?undefined:this[ig]==="true"};D("google.gdata.EntryLink.prototype.getReadOnly",Ag[t].Qe);Ag[t].Nb=function(a){gg(this,a===undefined?undefined:i(a))};D("google.gdata.EntryLink.prototype.setReadOnly",Ag[t].Nb);Ag[t].q=function(){return this.rel};D("google.gdata.EntryLink.prototype.getRel",Ag[t].q);
Ag[t].p=function(a){this.rel=a};D("google.gdata.EntryLink.prototype.setRel",Ag[t].p);var Bg=function(a){n(this,a?a[w]:this[w])};D("google.gdata.EventStatus",Bg);Bg[t].b=function(){return this[w]};D("google.gdata.EventStatus.prototype.getValue",Bg[t].b);Bg[t].a=function(a){n(this,a)};D("google.gdata.EventStatus.prototype.setValue",Bg[t].a);var Cg=E.namespace.GD+"#event.canceled";D("google.gdata.EventStatus.VALUE_CANCELED",Cg);var Dg=E.namespace.GD+"#event.confirmed";D("google.gdata.EventStatus.VALUE_CONFIRMED",Dg);var Eg=E.namespace.GD+"#event.tentative";
D("google.gdata.EventStatus.VALUE_TENTATIVE",Eg);var Fg=function(a){if(a){wa(this,a[qb]);this.realm=a.realm;n(this,a[w])}else{wa(this,this[qb]);this.realm=this.realm;n(this,this[w])}};D("google.gdata.ExtendedProperty",Fg);Fg[t].u=function(){return this[qb]};D("google.gdata.ExtendedProperty.prototype.getName",Fg[t].u);Fg[t].D=function(a){wa(this,a)};D("google.gdata.ExtendedProperty.prototype.setName",Fg[t].D);Fg[t].Mp=function(){return this.realm};D("google.gdata.ExtendedProperty.prototype.getRealm",Fg[t].Mp);Fg[t].Tr=function(a){this.realm=a};
D("google.gdata.ExtendedProperty.prototype.setRealm",Fg[t].Tr);var Gg=E.namespace.GD+"#shared";D("google.gdata.ExtendedProperty.REALM_SHARED",Gg);Fg[t].b=function(){return this[w]};D("google.gdata.ExtendedProperty.prototype.getValue",Fg[t].b);Fg[t].a=function(a){n(this,a)};D("google.gdata.ExtendedProperty.prototype.setValue",Fg[t].a);var K=function(a){if(!C(this.m))this.m=J;if(!C(this.Zk))this.Zk=dg;if(!C(this.Jl))this.Jl=eg;if(!C(this.Xl))this.Xl=fg;I[z](this,a);if(a){this.Pi(a.itemsPerPage);this.h(a.startIndex);this.Xj(a.totalResults)}else{this.openSearch$itemsPerPage=E.util.mutateTo(this.openSearch$itemsPerPage,this.Zk);this.openSearch$startIndex=E.util.mutateTo(this.openSearch$startIndex,this.Jl);this.openSearch$totalResults=E.util.mutateTo(this.openSearch$totalResults,this.Xl)}};D("google.gdata.Feed",K);K.e(I);K[t].Nf=E.app.namespace.APP;
D("google.gdata.Feed.prototype.xmlns$app",K[t].Nf);K[t].ha=E.opensearch.namespace.OPENSEARCH;D("google.gdata.Feed.prototype.xmlns$openSearch",K[t].ha);K[t].Bo=function(){return this.openSearch$itemsPerPage};D("google.gdata.Feed.prototype.getItemsPerPage",K[t].Bo);K[t].Pi=function(a){if(a&&a[u]===m)a=new this.Zk(a);this.openSearch$itemsPerPage=a};D("google.gdata.Feed.prototype.setItemsPerPage",K[t].Pi);K[t].i=function(){return this.openSearch$startIndex};
D("google.gdata.Feed.prototype.getStartIndex",K[t].i);K[t].h=function(a){if(a&&a[u]===m)a=new this.Jl(a);this.openSearch$startIndex=a};D("google.gdata.Feed.prototype.setStartIndex",K[t].h);K[t].Fq=function(){return this.openSearch$totalResults};D("google.gdata.Feed.prototype.getTotalResults",K[t].Fq);K[t].Xj=function(a){if(a&&a[u]===m)a=new this.Xl(a);this.openSearch$totalResults=a};D("google.gdata.Feed.prototype.setTotalResults",K[t].Xj);K[t].lb=function(){return this.g(Hg,"application/atom+xml")};
D("google.gdata.Feed.prototype.getEntryPostLink",K[t].lb);K[t].R=function(){return this.g(Ig,"application/atom+xml")};D("google.gdata.Feed.prototype.getFeedLink",K[t].R);K[t].ea=function(){return this.g("alternate","text/html")};D("google.gdata.Feed.prototype.getHtmlLink",K[t].ea);K[t].oc=function(){return this.g("self","application/atom+xml")};D("google.gdata.Feed.prototype.getSelfLink",K[t].oc);K[t].g=function(a,d){var e=E.util.vh(this.link,a,d);return e===undefined?undefined:this.link[e]};
D("google.gdata.Feed.prototype.getLink",K[t].g);K[t].od=function(a,d,e){if(!this[hg])return E.util.handleError(Error("feed is not associated with a GData service"),e);var h=this.lb();if(!h||!h[A])return E.util.handleError(Error("feed has no entry post link"),e);var j=h[A];return this[hg].od(j,a,d,e)};D("google.gdata.Feed.prototype.insertEntry",K[t].od);
K[t].ef=function(a,d){if(!this[hg])return E.util.handleError(Error("feed is not associated with a GData service"),d);var e=this.oc();if(!e||!e[A])return E.util.handleError(Error("feed has no self link"),d);var h=e[A];return this[hg].M(h,a,d)};D("google.gdata.Feed.prototype.getSelf",K[t].ef);var Jg=function(a){if(!C(this.Vb))this.Vb=K;if(a){this.ai(a.countHint);this.ri(a.feed);va(this,a[A]);this.Nb(a[ig]);this.rel=a.rel}else{this.countHint=this.countHint;this.feed=E.util.mutateTo(this.feed,this.Vb);va(this,this[A]);gg(this,this[ig]);this.rel=this.rel}};D("google.gdata.FeedLink",Jg);Jg[t].on=function(){return this.countHint===undefined?undefined:k(this.countHint)};D("google.gdata.FeedLink.prototype.getCountHint",Jg[t].on);Jg[t].ai=function(a){this.countHint=a===undefined?undefined:i(a)};
D("google.gdata.FeedLink.prototype.setCountHint",Jg[t].ai);Jg[t].M=function(){return this.feed};D("google.gdata.FeedLink.prototype.getFeed",Jg[t].M);Jg[t].ri=function(a){if(a&&a[u]===m)a=new this.Vb(a);this.feed=a};D("google.gdata.FeedLink.prototype.setFeed",Jg[t].ri);Jg[t].T=function(){return this[A]};D("google.gdata.FeedLink.prototype.getHref",Jg[t].T);Jg[t].N=function(a){va(this,a)};D("google.gdata.FeedLink.prototype.setHref",Jg[t].N);
Jg[t].Qe=function(){return this[ig]===undefined?undefined:this[ig]==="true"};D("google.gdata.FeedLink.prototype.getReadOnly",Jg[t].Qe);Jg[t].Nb=function(a){gg(this,a===undefined?undefined:i(a))};D("google.gdata.FeedLink.prototype.setReadOnly",Jg[t].Nb);Jg[t].q=function(){return this.rel};D("google.gdata.FeedLink.prototype.getRel",Jg[t].q);Jg[t].p=function(a){this.rel=a};D("google.gdata.FeedLink.prototype.setRel",Jg[t].p);var Kg=function(a){this.$t=a?a[w]:this.$t};D("google.gdata.FormattedAddress",Kg);Kg[t].b=function(){return this.$t};D("google.gdata.FormattedAddress.prototype.getValue",Kg[t].b);Kg[t].a=function(a){this.$t=a};D("google.gdata.FormattedAddress.prototype.setValue",Kg[t].a);var Lg=function(a){this.$t=a?a[w]:this.$t};D("google.gdata.HouseName",Lg);Lg[t].b=function(){return this.$t};D("google.gdata.HouseName.prototype.getValue",Lg[t].b);Lg[t].a=function(a){this.$t=a};D("google.gdata.HouseName.prototype.setValue",Lg[t].a);var Ng=function(a){if(a){this.address=a.address;xa(this,a[tb]);this.aa(a.primary);this.protocol=a[db];this.rel=a.rel}else{this.address=this.address;xa(this,this[tb]);this.primary=this.primary;this.protocol=this[db];this.rel=this.rel}};D("google.gdata.Im",Ng);Ng[t].ke=function(){return this.address};D("google.gdata.Im.prototype.getAddress",Ng[t].ke);Ng[t].Bf=function(a){this.address=a};D("google.gdata.Im.prototype.setAddress",Ng[t].Bf);Ng[t].I=function(){return this[tb]};
D("google.gdata.Im.prototype.getLabel",Ng[t].I);Ng[t].J=function(a){xa(this,a)};D("google.gdata.Im.prototype.setLabel",Ng[t].J);Ng[t].va=function(){return this.primary===undefined?undefined:this.primary==="true"};D("google.gdata.Im.prototype.getPrimary",Ng[t].va);Ng[t].aa=function(a){this.primary=a===undefined?undefined:i(a)};D("google.gdata.Im.prototype.setPrimary",Ng[t].aa);Ng[t].Hp=function(){return this[db]};D("google.gdata.Im.prototype.getProtocol",Ng[t].Hp);
Ng[t].Sr=function(a){this.protocol=a};D("google.gdata.Im.prototype.setProtocol",Ng[t].Sr);var Og=E.namespace.GD+"#AIM";D("google.gdata.Im.PROTOCOL_AIM",Og);var Pg=E.namespace.GD+"#GOOGLE_TALK";D("google.gdata.Im.PROTOCOL_GOOGLE_TALK",Pg);var Qg=E.namespace.GD+"#ICQ";D("google.gdata.Im.PROTOCOL_ICQ",Qg);var Rg=E.namespace.GD+"#JABBER";D("google.gdata.Im.PROTOCOL_JABBER",Rg);var Sg=E.namespace.GD+"#MSN";D("google.gdata.Im.PROTOCOL_MSN",Sg);var Tg=E.namespace.GD+"#QQ";
D("google.gdata.Im.PROTOCOL_QQ",Tg);var Ug=E.namespace.GD+"#SKYPE";D("google.gdata.Im.PROTOCOL_SKYPE",Ug);var Vg=E.namespace.GD+"#YAHOO";D("google.gdata.Im.PROTOCOL_YAHOO",Vg);Ng[t].q=function(){return this.rel};D("google.gdata.Im.prototype.getRel",Ng[t].q);Ng[t].p=function(a){this.rel=a};D("google.gdata.Im.prototype.setRel",Ng[t].p);var Wg=E.namespace.GD+"#home";D("google.gdata.Im.REL_HOME",Wg);var Xg=E.namespace.GD+"#other";D("google.gdata.Im.REL_OTHER",Xg);var Yg=E.namespace.GD+"#work";
D("google.gdata.Im.REL_WORK",Yg);var Zg=function(a){Jf[z](this,a);for(var d=["xml$lang"],e=0;e<d[r];e++){var h=d[e];h in this&&!C(this[h])&&delete this[h]}};D("google.gdata.Kind",Zg);Zg.e(Jf);var $g=E.namespace.GD+"#kind";D("google.gdata.Kind.SCHEME_KIND",$g);var ah=function(a){if(a)this.a(a[w]);else this.$t=this.$t};D("google.gdata.LastViewed",ah);ah[t].b=function(){return this.$t===undefined?undefined:G(this.$t)};D("google.gdata.LastViewed.prototype.getValue",ah[t].b);ah[t].a=function(a){this.$t=a===undefined?undefined:gf(a)};D("google.gdata.LastViewed.prototype.setValue",ah[t].a);var bh=function(a){Nf[z](this,a)};D("google.gdata.Link",bh);bh.e(Nf);var Hg=E.namespace.GD+"#post";D("google.gdata.Link.REL_ENTRY_POST",Hg);var Ig=E.namespace.GD+"#feed";D("google.gdata.Link.REL_FEED",Ig);var ch=E.namespace.GD+"#batch";D("google.gdata.Link.REL_FEED_BATCH",ch);var dh=function(a,d,e,h){var j=new bh;j.p(a);j.l(d);j.N(e);j.K(h);return j};D("google.gdata.Link.create",dh);var eh=function(a){Zg[z](this,a);for(var d=["label"],e=0;e<d[r];e++){var h=d[e];h in this&&!C(this[h])&&delete this[h]}};D("google.gdata.MessageKind",eh);eh.e(Zg);var fh=E.namespace.GD+"#message";D("google.gdata.MessageKind.TERM_MESSAGE",fh);var gh=function(a){if(a){this.Mh(a.amount);this.currencyCode=a.currencyCode}else{this.amount=this.amount;this.currencyCode=this.currencyCode}};D("google.gdata.Money",gh);gh[t].Hm=function(){return this.amount===undefined?undefined:k(this.amount)};D("google.gdata.Money.prototype.getAmount",gh[t].Hm);gh[t].Mh=function(a){this.amount=a===undefined?undefined:i(a)};D("google.gdata.Money.prototype.setAmount",gh[t].Mh);gh[t].ve=function(){return this.currencyCode};
D("google.gdata.Money.prototype.getCurrencyCode",gh[t].ve);gh[t].Ef=function(a){this.currencyCode=a};D("google.gdata.Money.prototype.setCurrencyCode",gh[t].Ef);var hh=function(a){this.$t=a?a[w]:this.$t};D("google.gdata.Neighborhood",hh);hh[t].b=function(){return this.$t};D("google.gdata.Neighborhood.prototype.getValue",hh[t].b);hh[t].a=function(a){this.$t=a};D("google.gdata.Neighborhood.prototype.setValue",hh[t].a);var ih=function(a){if(a){this.qd=a.qd;this.orderId=a.orderId;this.prev=a.prev;this.ref=a.ref;this.rel=a.rel}else{this.qd=this.qd;this.orderId=this.orderId;this.prev=this.prev;this.ref=this.ref;this.rel=this.rel}};D("google.gdata.Ordering",ih);ih[t].bp=function(){return this.qd};D("google.gdata.Ordering.prototype.getNext",ih[t].bp);ih[t].Lr=function(a){this.qd=a};D("google.gdata.Ordering.prototype.setNext",ih[t].Lr);ih[t].ep=function(){return this.orderId};
D("google.gdata.Ordering.prototype.getOrderId",ih[t].ep);ih[t].Nr=function(a){this.orderId=a};D("google.gdata.Ordering.prototype.setOrderId",ih[t].Nr);ih[t].Dp=function(){return this.prev};D("google.gdata.Ordering.prototype.getPrev",ih[t].Dp);ih[t].Qr=function(a){this.prev=a};D("google.gdata.Ordering.prototype.setPrev",ih[t].Qr);ih[t].Re=function(){return this.ref};D("google.gdata.Ordering.prototype.getRef",ih[t].Re);ih[t].Jf=function(a){this.ref=a};D("google.gdata.Ordering.prototype.setRef",ih[t].Jf);
ih[t].q=function(){return this.rel};D("google.gdata.Ordering.prototype.getRel",ih[t].q);ih[t].p=function(a){this.rel=a};D("google.gdata.Ordering.prototype.setRel",ih[t].p);D("google.gdata.Ordering.REL_COMESAFTER","comesAfter");D("google.gdata.Ordering.REL_FIRST","first");D("google.gdata.Ordering.REL_LAST","last");var jh=function(a){this.$t=a?a[w]:this.$t};D("google.gdata.OrgName",jh);jh[t].b=function(){return this.$t};D("google.gdata.OrgName.prototype.getValue",jh[t].b);jh[t].a=function(a){this.$t=a};D("google.gdata.OrgName.prototype.setValue",jh[t].a);var kh=function(a){this.$t=a?a[w]:this.$t};D("google.gdata.OrgTitle",kh);kh[t].b=function(){return this.$t};D("google.gdata.OrgTitle.prototype.getValue",kh[t].b);kh[t].a=function(a){this.$t=a};D("google.gdata.OrgTitle.prototype.setValue",kh[t].a);var lh=function(a){if(!C(this.fl))this.fl=jh;if(!C(this.gl))this.gl=kh;if(a){xa(this,a[tb]);this.aj(a.orgName);this.bj(a.orgTitle);this.aa(a.primary);this.rel=a.rel}else{xa(this,this[tb]);this.gd$orgName=E.util.mutateTo(this.gd$orgName,this.fl);this.gd$orgTitle=E.util.mutateTo(this.gd$orgTitle,this.gl);this.primary=this.primary;this.rel=this.rel}};D("google.gdata.Organization",lh);lh[t].I=function(){return this[tb]};D("google.gdata.Organization.prototype.getLabel",lh[t].I);
lh[t].J=function(a){xa(this,a)};D("google.gdata.Organization.prototype.setLabel",lh[t].J);lh[t].fp=function(){return this.gd$orgName};D("google.gdata.Organization.prototype.getOrgName",lh[t].fp);lh[t].aj=function(a){if(a&&a[u]===m)a=new this.fl(a);this.gd$orgName=a};D("google.gdata.Organization.prototype.setOrgName",lh[t].aj);lh[t].gp=function(){return this.gd$orgTitle};D("google.gdata.Organization.prototype.getOrgTitle",lh[t].gp);
lh[t].bj=function(a){if(a&&a[u]===m)a=new this.gl(a);this.gd$orgTitle=a};D("google.gdata.Organization.prototype.setOrgTitle",lh[t].bj);lh[t].va=function(){return this.primary===undefined?undefined:this.primary==="true"};D("google.gdata.Organization.prototype.getPrimary",lh[t].va);lh[t].aa=function(a){this.primary=a===undefined?undefined:i(a)};D("google.gdata.Organization.prototype.setPrimary",lh[t].aa);lh[t].q=function(){return this.rel};D("google.gdata.Organization.prototype.getRel",lh[t].q);
lh[t].p=function(a){this.rel=a};D("google.gdata.Organization.prototype.setRel",lh[t].p);var mh=E.namespace.GD+"#other";D("google.gdata.Organization.REL_OTHER",mh);var nh=E.namespace.GD+"#work";D("google.gdata.Organization.REL_WORK",nh);var oh=function(a){this.fields=a?a.fields:this.fields};D("google.gdata.Partial",oh);oh[t].Pn=function(){return this.fields};D("google.gdata.Partial.prototype.getFields",oh[t].Pn);oh[t].or=function(a){this.fields=a};D("google.gdata.Partial.prototype.setFields",oh[t].or);var ph=function(a){if(a){xa(this,a[tb]);this.aa(a.primary);this.rel=a.rel;this.$t=a[w]}else{xa(this,this[tb]);this.primary=this.primary;this.rel=this.rel;this.$t=this.$t}};D("google.gdata.PhoneNumber",ph);ph[t].I=function(){return this[tb]};D("google.gdata.PhoneNumber.prototype.getLabel",ph[t].I);ph[t].J=function(a){xa(this,a)};D("google.gdata.PhoneNumber.prototype.setLabel",ph[t].J);ph[t].va=function(){return this.primary===undefined?undefined:this.primary==="true"};
D("google.gdata.PhoneNumber.prototype.getPrimary",ph[t].va);ph[t].aa=function(a){this.primary=a===undefined?undefined:i(a)};D("google.gdata.PhoneNumber.prototype.setPrimary",ph[t].aa);ph[t].q=function(){return this.rel};D("google.gdata.PhoneNumber.prototype.getRel",ph[t].q);ph[t].p=function(a){this.rel=a};D("google.gdata.PhoneNumber.prototype.setRel",ph[t].p);var qh=E.namespace.GD+"#fax";D("google.gdata.PhoneNumber.REL_FAX",qh);var rh=E.namespace.GD+"#home";D("google.gdata.PhoneNumber.REL_HOME",rh);
var sh=E.namespace.GD+"#home_fax";D("google.gdata.PhoneNumber.REL_HOME_FAX",sh);var th=E.namespace.GD+"#mobile";D("google.gdata.PhoneNumber.REL_MOBILE",th);var uh=E.namespace.GD+"#other";D("google.gdata.PhoneNumber.REL_OTHER",uh);var vh=E.namespace.GD+"#pager";D("google.gdata.PhoneNumber.REL_PAGER",vh);var wh=E.namespace.GD+"#work";D("google.gdata.PhoneNumber.REL_WORK",wh);var xh=E.namespace.GD+"#work_fax";D("google.gdata.PhoneNumber.REL_WORK_FAX",xh);ph[t].b=function(){return this.$t};
D("google.gdata.PhoneNumber.prototype.getValue",ph[t].b);ph[t].a=function(a){this.$t=a};D("google.gdata.PhoneNumber.prototype.setValue",ph[t].a);var yh=function(a){this.$t=a?a[w]:this.$t};D("google.gdata.PoBox",yh);yh[t].b=function(){return this.$t};D("google.gdata.PoBox.prototype.getValue",yh[t].b);yh[t].a=function(a){this.$t=a};D("google.gdata.PoBox.prototype.setValue",yh[t].a);var zh=function(a){this.$t=a?a[w]:this.$t};D("google.gdata.PostCode",zh);zh[t].b=function(){return this.$t};D("google.gdata.PostCode.prototype.getValue",zh[t].b);zh[t].a=function(a){this.$t=a};D("google.gdata.PostCode.prototype.setValue",zh[t].a);var Ah=function(a){if(a){xa(this,a[tb]);this.aa(a.primary);this.rel=a.rel;this.$t=a[w]}else{xa(this,this[tb]);this.primary=this.primary;this.rel=this.rel;this.$t=this.$t}};D("google.gdata.PostalAddress",Ah);Ah[t].I=function(){return this[tb]};D("google.gdata.PostalAddress.prototype.getLabel",Ah[t].I);Ah[t].J=function(a){xa(this,a)};D("google.gdata.PostalAddress.prototype.setLabel",Ah[t].J);Ah[t].va=function(){return this.primary===undefined?undefined:this.primary==="true"};
D("google.gdata.PostalAddress.prototype.getPrimary",Ah[t].va);Ah[t].aa=function(a){this.primary=a===undefined?undefined:i(a)};D("google.gdata.PostalAddress.prototype.setPrimary",Ah[t].aa);Ah[t].q=function(){return this.rel};D("google.gdata.PostalAddress.prototype.getRel",Ah[t].q);Ah[t].p=function(a){this.rel=a};D("google.gdata.PostalAddress.prototype.setRel",Ah[t].p);var Bh=E.namespace.GD+"#home";D("google.gdata.PostalAddress.REL_HOME",Bh);var Ch=E.namespace.GD+"#other";
D("google.gdata.PostalAddress.REL_OTHER",Ch);var Dh=E.namespace.GD+"#work";D("google.gdata.PostalAddress.REL_WORK",Dh);Ah[t].b=function(){return this.$t};D("google.gdata.PostalAddress.prototype.getValue",Ah[t].b);Ah[t].a=function(a){this.$t=a};D("google.gdata.PostalAddress.prototype.setValue",Ah[t].a);var Eh=function(a){if(a)this.a(a[w]);else this.$t=this.$t};D("google.gdata.QuotaBytesUsed",Eh);Eh[t].b=function(){return this.$t===undefined?undefined:k(this.$t)};D("google.gdata.QuotaBytesUsed.prototype.getValue",Eh[t].b);Eh[t].a=function(a){this.$t=a===undefined?undefined:i(a)};D("google.gdata.QuotaBytesUsed.prototype.setValue",Eh[t].a);var Fh=function(a){if(a){this.Qh(a.average);this.Wi(a.max);this.Yi(a.min);this.$i(a.numRaters);this.rel=a.rel;this.a(a[w])}else{this.average=this.average;this.max=this.max;this.min=this.min;this.numRaters=this.numRaters;this.rel=this.rel;n(this,this[w])}};D("google.gdata.Rating",Fh);Fh[t].Nm=function(){return this.average===undefined?undefined:k(this.average)};D("google.gdata.Rating.prototype.getAverage",Fh[t].Nm);Fh[t].Qh=function(a){this.average=a===undefined?undefined:i(a)};
D("google.gdata.Rating.prototype.setAverage",Fh[t].Qh);Fh[t].Po=function(){return this.max===undefined?undefined:k(this.max)};D("google.gdata.Rating.prototype.getMax",Fh[t].Po);Fh[t].Wi=function(a){this.max=a===undefined?undefined:i(a)};D("google.gdata.Rating.prototype.setMax",Fh[t].Wi);Fh[t].Yo=function(){return this.min===undefined?undefined:k(this.min)};D("google.gdata.Rating.prototype.getMin",Fh[t].Yo);Fh[t].Yi=function(a){this.min=a===undefined?undefined:i(a)};
D("google.gdata.Rating.prototype.setMin",Fh[t].Yi);Fh[t].dp=function(){return this.numRaters===undefined?undefined:k(this.numRaters)};D("google.gdata.Rating.prototype.getNumRaters",Fh[t].dp);Fh[t].$i=function(a){this.numRaters=a===undefined?undefined:i(a)};D("google.gdata.Rating.prototype.setNumRaters",Fh[t].$i);Fh[t].q=function(){return this.rel};D("google.gdata.Rating.prototype.getRel",Fh[t].q);Fh[t].p=function(a){this.rel=a};D("google.gdata.Rating.prototype.setRel",Fh[t].p);
var Gh=E.namespace.GD+"#overall";D("google.gdata.Rating.REL_OVERALL",Gh);var Hh=E.namespace.GD+"#price";D("google.gdata.Rating.REL_PRICE",Hh);var Ih=E.namespace.GD+"#quality";D("google.gdata.Rating.REL_QUALITY",Ih);Fh[t].b=function(){return this[w]===undefined?undefined:k(this[w])};D("google.gdata.Rating.prototype.getValue",Fh[t].b);Fh[t].a=function(a){n(this,a===undefined?undefined:i(a))};D("google.gdata.Rating.prototype.setValue",Fh[t].a);var Jh=function(a){this.$t=a?a[w]:this.$t};D("google.gdata.Recurrence",Jh);Jh[t].b=function(){return this.$t};D("google.gdata.Recurrence.prototype.getValue",Jh[t].b);Jh[t].a=function(a){this.$t=a};D("google.gdata.Recurrence.prototype.setValue",Jh[t].a);var Kh=function(a){this.$t=a?a[w]:this.$t};D("google.gdata.Region",Kh);Kh[t].b=function(){return this.$t};D("google.gdata.Region.prototype.getValue",Kh[t].b);Kh[t].a=function(a){this.$t=a};D("google.gdata.Region.prototype.setValue",Kh[t].a);var Lh=function(a){if(a){this.Gh(a.absoluteTime);this.ei(a.days);this.setHours(a.hours);this.method=a.method;this.setMinutes(a.minutes)}else{this.absoluteTime=this.absoluteTime;this.days=this.days;this.hours=this.hours;this.method=this.method;this.minutes=this.minutes}};D("google.gdata.Reminder",Lh);Lh[t].vm=function(){return this.absoluteTime===undefined?undefined:G(this.absoluteTime)};D("google.gdata.Reminder.prototype.getAbsoluteTime",Lh[t].vm);
Lh[t].Gh=function(a){this.absoluteTime=a===undefined?undefined:gf(a)};D("google.gdata.Reminder.prototype.setAbsoluteTime",Lh[t].Gh);Lh[t].un=function(){return this.days===undefined?undefined:k(this.days)};D("google.gdata.Reminder.prototype.getDays",Lh[t].un);Lh[t].ei=function(a){this.days=a===undefined?undefined:i(a)};D("google.gdata.Reminder.prototype.setDays",Lh[t].ei);Lh[t].getHours=function(){return this.hours===undefined?undefined:k(this.hours)};D("google.gdata.Reminder.prototype.getHours",Lh[t].getHours);
Lh[t].setHours=function(a){this.hours=a===undefined?undefined:i(a)};D("google.gdata.Reminder.prototype.setHours",Lh[t].setHours);Lh[t].Wo=function(){return this.method};D("google.gdata.Reminder.prototype.getMethod",Lh[t].Wo);Lh[t].Hr=function(a){this.method=a};D("google.gdata.Reminder.prototype.setMethod",Lh[t].Hr);D("google.gdata.Reminder.METHOD_ALERT","alert");D("google.gdata.Reminder.METHOD_ALL","all");D("google.gdata.Reminder.METHOD_EMAIL","email");D("google.gdata.Reminder.METHOD_NONE","none");
D("google.gdata.Reminder.METHOD_SMS","sms");Lh[t].getMinutes=function(){return this.minutes===undefined?undefined:k(this.minutes)};D("google.gdata.Reminder.prototype.getMinutes",Lh[t].getMinutes);Lh[t].setMinutes=function(a){this.minutes=a===undefined?undefined:i(a)};D("google.gdata.Reminder.prototype.setMinutes",Lh[t].setMinutes);var Mh=function(a){this.$t=a?a[w]:this.$t};D("google.gdata.ResourceId",Mh);Mh[t].b=function(){return this.$t};D("google.gdata.ResourceId.prototype.getValue",Mh[t].b);Mh[t].a=function(a){this.$t=a};D("google.gdata.ResourceId.prototype.setValue",Mh[t].a);var Nh=function(a){this.$t=a?a[w]:this.$t};D("google.gdata.Street",Nh);Nh[t].b=function(){return this.$t};D("google.gdata.Street.prototype.getValue",Nh[t].b);Nh[t].a=function(a){this.$t=a};D("google.gdata.Street.prototype.setValue",Nh[t].a);var Oh=function(a){this.$t=a?a[w]:this.$t};D("google.gdata.Subregion",Oh);Oh[t].b=function(){return this.$t};D("google.gdata.Subregion.prototype.getValue",Oh[t].b);Oh[t].a=function(a){this.$t=a};D("google.gdata.Subregion.prototype.setValue",Oh[t].a);var Ph=function(a){n(this,a?a[w]:this[w])};D("google.gdata.Transparency",Ph);Ph[t].b=function(){return this[w]};D("google.gdata.Transparency.prototype.getValue",Ph[t].b);Ph[t].a=function(a){n(this,a)};D("google.gdata.Transparency.prototype.setValue",Ph[t].a);var Qh=E.namespace.GD+"#event.opaque";D("google.gdata.Transparency.VALUE_OPAQUE",Qh);var Rh=E.namespace.GD+"#event.transparent";D("google.gdata.Transparency.VALUE_TRANSPARENT",Rh);var Sh=function(a){n(this,a?a[w]:this[w])};D("google.gdata.Visibility",Sh);Sh[t].b=function(){return this[w]};D("google.gdata.Visibility.prototype.getValue",Sh[t].b);Sh[t].a=function(a){n(this,a)};D("google.gdata.Visibility.prototype.setValue",Sh[t].a);var Th=E.namespace.GD+"#event.confidential";D("google.gdata.Visibility.VALUE_CONFIDENTIAL",Th);var Uh=E.namespace.GD+"#event.default";D("google.gdata.Visibility.VALUE_DEFAULT",Uh);var Vh=E.namespace.GD+"#event.private";
D("google.gdata.Visibility.VALUE_PRIVATE",Vh);var Wh=E.namespace.GD+"#event.public";D("google.gdata.Visibility.VALUE_PUBLIC",Wh);var Xh=function(a){if(!C(this.Al))this.Al=Lh;if(a){this.ni(a.endTime);this.Aj(a.reminder);this.Kj(a.startTime);this.valueString=a.valueString}else{this.endTime=this.endTime;if(this.gd$reminder)for(var d=this.gd$reminder,e=0;e<d[r];e++)this.gd$reminder[e]=E.util.mutateTo(d[e],this.Al);else this.gd$reminder=[];this.startTime=this.startTime;this.valueString=this.valueString}};D("google.gdata.When",Xh);Xh[t].En=function(){return this.endTime===undefined?undefined:G(this.endTime)};
D("google.gdata.When.prototype.getEndTime",Xh[t].En);Xh[t].ni=function(a){this.endTime=a===undefined?undefined:gf(a)};D("google.gdata.When.prototype.setEndTime",Xh[t].ni);Xh[t].Tp=function(){return this.gd$reminder};D("google.gdata.When.prototype.getReminder",Xh[t].Tp);Xh[t].Aj=function(a){this.gd$reminder=[];if(a)for(var d=0;d<a[r];d++)this.dc(a[d])};D("google.gdata.When.prototype.setReminder",Xh[t].Aj);Xh[t].dc=function(a){if(a[u]===m)a=new this.Al(a);this.gd$reminder[q](a)};
D("google.gdata.When.prototype.addReminder",Xh[t].dc);Xh[t].oq=function(){return this.startTime===undefined?undefined:G(this.startTime)};D("google.gdata.When.prototype.getStartTime",Xh[t].oq);Xh[t].Kj=function(a){this.startTime=a===undefined?undefined:gf(a)};D("google.gdata.When.prototype.setStartTime",Xh[t].Kj);Xh[t].Hb=function(){return this.valueString};D("google.gdata.When.prototype.getValueString",Xh[t].Hb);Xh[t].Pb=function(a){this.valueString=a};
D("google.gdata.When.prototype.setValueString",Xh[t].Pb);var Yh=function(a){if(!C(this.eb))this.eb=Ag;if(a){this.bb(a.entryLink);xa(this,a[tb]);this.rel=a.rel;this.valueString=a.valueString}else{this.gd$entryLink=E.util.mutateTo(this.gd$entryLink,this.eb);xa(this,this[tb]);this.rel=this.rel;this.valueString=this.valueString}};D("google.gdata.Where",Yh);Yh[t].kb=function(){return this.gd$entryLink};D("google.gdata.Where.prototype.getEntryLink",Yh[t].kb);Yh[t].bb=function(a){if(a&&a[u]===m)a=new this.eb(a);this.gd$entryLink=a};
D("google.gdata.Where.prototype.setEntryLink",Yh[t].bb);Yh[t].I=function(){return this[tb]};D("google.gdata.Where.prototype.getLabel",Yh[t].I);Yh[t].J=function(a){xa(this,a)};D("google.gdata.Where.prototype.setLabel",Yh[t].J);Yh[t].q=function(){return this.rel};D("google.gdata.Where.prototype.getRel",Yh[t].q);Yh[t].p=function(a){this.rel=a};D("google.gdata.Where.prototype.setRel",Yh[t].p);var Zh=E.namespace.GD+"#event";D("google.gdata.Where.REL_EVENT",Zh);var $h=E.namespace.GD+"#event.alternate";
D("google.gdata.Where.REL_EVENT_ALTERNATE",$h);var ai=E.namespace.GD+"#event.parking";D("google.gdata.Where.REL_EVENT_PARKING",ai);Yh[t].Hb=function(){return this.valueString};D("google.gdata.Where.prototype.getValueString",Yh[t].Hb);Yh[t].Pb=function(a){this.valueString=a};D("google.gdata.Where.prototype.setValueString",Yh[t].Pb);var bi=function(a){if(!C(this.lk))this.lk=kg;if(!C(this.mk))this.mk=pg;if(!C(this.eb))this.eb=Ag;if(a){this.Oh(a.attendeeStatus);this.Ph(a.attendeeType);this.email=a.email;this.bb(a.entryLink);this.rel=a.rel;this.valueString=a.valueString}else{this.gd$attendeeStatus=E.util.mutateTo(this.gd$attendeeStatus,this.lk);this.gd$attendeeType=E.util.mutateTo(this.gd$attendeeType,this.mk);this.email=this.email;this.gd$entryLink=E.util.mutateTo(this.gd$entryLink,this.eb);this.rel=this.rel;this.valueString=this.valueString}};
D("google.gdata.Who",bi);bi[t].Jm=function(){return this.gd$attendeeStatus};D("google.gdata.Who.prototype.getAttendeeStatus",bi[t].Jm);bi[t].Oh=function(a){if(a&&a[u]===m)a=new this.lk(a);this.gd$attendeeStatus=a};D("google.gdata.Who.prototype.setAttendeeStatus",bi[t].Oh);bi[t].Km=function(){return this.gd$attendeeType};D("google.gdata.Who.prototype.getAttendeeType",bi[t].Km);bi[t].Ph=function(a){if(a&&a[u]===m)a=new this.mk(a);this.gd$attendeeType=a};
D("google.gdata.Who.prototype.setAttendeeType",bi[t].Ph);bi[t].ye=function(){return this.email};D("google.gdata.Who.prototype.getEmail",bi[t].ye);bi[t].ud=function(a){this.email=a};D("google.gdata.Who.prototype.setEmail",bi[t].ud);bi[t].kb=function(){return this.gd$entryLink};D("google.gdata.Who.prototype.getEntryLink",bi[t].kb);bi[t].bb=function(a){if(a&&a[u]===m)a=new this.eb(a);this.gd$entryLink=a};D("google.gdata.Who.prototype.setEntryLink",bi[t].bb);bi[t].q=function(){return this.rel};
D("google.gdata.Who.prototype.getRel",bi[t].q);bi[t].p=function(a){this.rel=a};D("google.gdata.Who.prototype.setRel",bi[t].p);var ci=E.namespace.GD+"#event.attendee";D("google.gdata.Who.REL_EVENT_ATTENDEE",ci);var di=E.namespace.GD+"#event.organizer";D("google.gdata.Who.REL_EVENT_ORGANIZER",di);var ei=E.namespace.GD+"#event.performer";D("google.gdata.Who.REL_EVENT_PERFORMER",ei);var fi=E.namespace.GD+"#event.speaker";D("google.gdata.Who.REL_EVENT_SPEAKER",fi);var gi=E.namespace.GD+"#message.bcc";
D("google.gdata.Who.REL_MESSAGE_BCC",gi);var hi=E.namespace.GD+"#message.cc";D("google.gdata.Who.REL_MESSAGE_CC",hi);var ii=E.namespace.GD+"#message.from";D("google.gdata.Who.REL_MESSAGE_FROM",ii);var ji=E.namespace.GD+"#message.reply-to";D("google.gdata.Who.REL_MESSAGE_REPLY_TO",ji);var ki=E.namespace.GD+"#message.to";D("google.gdata.Who.REL_MESSAGE_TO",ki);var li=E.namespace.GD+"#task.assigned-to";D("google.gdata.Who.REL_TASK_ASSIGNED_TO",li);bi[t].Hb=function(){return this.valueString};
D("google.gdata.Who.prototype.getValueString",bi[t].Hb);bi[t].Pb=function(a){this.valueString=a};D("google.gdata.Who.prototype.setValueString",bi[t].Pb);var mi=function(a){if(!C(this.za))this.za=Jg;if(a)this.ma(a.feedLink);else this.gd$feedLink=E.util.mutateTo(this.gd$feedLink,this.za)};D("google.gdata.Comments",mi);mi[t].R=function(){return this.gd$feedLink};D("google.gdata.Comments.prototype.getFeedLink",mi[t].R);mi[t].ma=function(a){if(a&&a[u]===m)a=new this.za(a);this.gd$feedLink=a};D("google.gdata.Comments.prototype.setFeedLink",mi[t].ma);var ni=function(a){Zg[z](this,a);for(var d=["label"],e=0;e<d[r];e++){var h=d[e];h in this&&!C(this[h])&&delete this[h]}};D("google.gdata.EventKind",ni);ni.e(Zg);var oi=E.namespace.GD+"#event";D("google.gdata.EventKind.TERM_EVENT",oi);var pi=function(a){if(!C(this.il))this.il=Xh;if(a){va(this,a[A]);this.id=a.originalId;this.dj(a.originalStartTime)}else{va(this,this[A]);this.id=this.id;this.gd$when=E.util.mutateTo(this.gd$when,this.il)}};D("google.gdata.OriginalEvent",pi);pi[t].T=function(){return this[A]};D("google.gdata.OriginalEvent.prototype.getHref",pi[t].T);pi[t].N=function(a){va(this,a)};D("google.gdata.OriginalEvent.prototype.setHref",pi[t].N);pi[t].ip=function(){return this.id};
D("google.gdata.OriginalEvent.prototype.getOriginalId",pi[t].ip);pi[t].Or=function(a){this.id=a};D("google.gdata.OriginalEvent.prototype.setOriginalId",pi[t].Or);pi[t].jp=function(){return this.gd$when};D("google.gdata.OriginalEvent.prototype.getOriginalStartTime",pi[t].jp);pi[t].dj=function(a){if(a&&a[u]===m)a=new this.il(a);this.gd$when=a};D("google.gdata.OriginalEvent.prototype.setOriginalStartTime",pi[t].dj);var L=function(a){if(!C(this.tb))this.tb=mi;if(!C(this.Kd))this.Kd=Bg;if(!C(this.Sd))this.Sd=pi;if(!C(this.ee))this.ee=Ph;if(!C(this.he))this.he=Sh;if(!C(this.dm))this.dm=Xh;if(!C(this.em))this.em=Yh;if(!C(this.ng))this.ng=bi;J[z](this,a);if(a){this.wc(a.comments);this.Dc(a.eventStatus);this.Lc(a.originalEvent);this.fd(a.transparency);this.hd(a.visibility);this.bk(a.when);this.ck(a.where);this.dk(a.who)}else{this.gd$comments=E.util.mutateTo(this.gd$comments,this.tb);this.gd$eventStatus=E.util.mutateTo(this.gd$eventStatus,
this.Kd);this.gd$originalEvent=E.util.mutateTo(this.gd$originalEvent,this.Sd);this.gd$transparency=E.util.mutateTo(this.gd$transparency,this.ee);this.gd$visibility=E.util.mutateTo(this.gd$visibility,this.he);if(this.gd$when)for(var d=this.gd$when,e=0;e<d[r];e++)this.gd$when[e]=E.util.mutateTo(d[e],this.dm);else this.gd$when=[];if(this.gd$where){d=this.gd$where;for(e=0;e<d[r];e++)this.gd$where[e]=E.util.mutateTo(d[e],this.em)}else this.gd$where=[];if(this.gd$who){d=this.gd$who;for(e=0;e<d[r];e++)this.gd$who[e]=
E.util.mutateTo(d[e],this.ng)}else this.gd$who=[]}var h=["app$control","summary","rights","app$edited"];for(e=0;e<h[r];e++){var j=h[e];j in this&&!C(this[j])&&delete this[j]}};D("google.gdata.RecurrenceExceptionEntry",L);L.e(J);L[t].f=E.namespace.GD;D("google.gdata.RecurrenceExceptionEntry.prototype.xmlns$gd",L[t].f);L[t].ha=E.opensearch.namespace.OPENSEARCH;D("google.gdata.RecurrenceExceptionEntry.prototype.xmlns$openSearch",L[t].ha);L[t].pe=function(){return this.gd$comments};
D("google.gdata.RecurrenceExceptionEntry.prototype.getComments",L[t].pe);L[t].wc=function(a){if(a&&a[u]===m)a=new this.tb(a);this.gd$comments=a};D("google.gdata.RecurrenceExceptionEntry.prototype.setComments",L[t].wc);L[t].Ae=function(){return this.gd$eventStatus};D("google.gdata.RecurrenceExceptionEntry.prototype.getEventStatus",L[t].Ae);L[t].Dc=function(a){if(a&&a[u]===m)a=new this.Kd(a);this.gd$eventStatus=a};D("google.gdata.RecurrenceExceptionEntry.prototype.setEventStatus",L[t].Dc);L[t].Le=function(){return this.gd$originalEvent};
D("google.gdata.RecurrenceExceptionEntry.prototype.getOriginalEvent",L[t].Le);L[t].Lc=function(a){if(a&&a[u]===m)a=new this.Sd(a);this.gd$originalEvent=a};D("google.gdata.RecurrenceExceptionEntry.prototype.setOriginalEvent",L[t].Lc);L[t].rf=function(){return this.gd$transparency};D("google.gdata.RecurrenceExceptionEntry.prototype.getTransparency",L[t].rf);L[t].fd=function(a){if(a&&a[u]===m)a=new this.ee(a);this.gd$transparency=a};
D("google.gdata.RecurrenceExceptionEntry.prototype.setTransparency",L[t].fd);L[t].uf=function(){return this.gd$visibility};D("google.gdata.RecurrenceExceptionEntry.prototype.getVisibility",L[t].uf);L[t].hd=function(a){if(a&&a[u]===m)a=new this.he(a);this.gd$visibility=a};D("google.gdata.RecurrenceExceptionEntry.prototype.setVisibility",L[t].hd);L[t].Pq=function(){return this.gd$when};D("google.gdata.RecurrenceExceptionEntry.prototype.getWhen",L[t].Pq);
L[t].bk=function(a){this.gd$when=[];if(a)for(var d=0;d<a[r];d++)this.hh(a[d])};D("google.gdata.RecurrenceExceptionEntry.prototype.setWhen",L[t].bk);L[t].hh=function(a){if(a[u]===m)a=new this.dm(a);this.gd$when[q](a)};D("google.gdata.RecurrenceExceptionEntry.prototype.addWhen",L[t].hh);L[t].Qq=function(){return this.gd$where};D("google.gdata.RecurrenceExceptionEntry.prototype.getWhere",L[t].Qq);L[t].ck=function(a){this.gd$where=[];if(a)for(var d=0;d<a[r];d++)this.ih(a[d])};
D("google.gdata.RecurrenceExceptionEntry.prototype.setWhere",L[t].ck);L[t].ih=function(a){if(a[u]===m)a=new this.em(a);this.gd$where[q](a)};D("google.gdata.RecurrenceExceptionEntry.prototype.addWhere",L[t].ih);L[t].Rq=function(){return this.gd$who};D("google.gdata.RecurrenceExceptionEntry.prototype.getWho",L[t].Rq);L[t].dk=function(a){this.gd$who=[];if(a)for(var d=0;d<a[r];d++)this.jh(a[d])};D("google.gdata.RecurrenceExceptionEntry.prototype.setWho",L[t].dk);
L[t].jh=function(a){if(a[u]===m)a=new this.ng(a);this.gd$who[q](a)};D("google.gdata.RecurrenceExceptionEntry.prototype.addWho",L[t].jh);var qi=function(a){if(!C(this.Jd))this.Jd=L;Ag[z](this,a);for(var d=["readOnly","rel","href"],e=0;e<d[r];e++){var h=d[e];h in this&&!C(this[h])&&delete this[h]}};D("google.gdata.RecurrenceExceptionEntryLink",qi);qi.e(Ag);var O=function(a){if(!C(this.hk))this.hk=jg;if(!C(this.pk))this.pk=sg;if(!C(this.uk))this.uk=tg;if(!C(this.Jk))this.Jk=Kg;if(!C(this.Uk))this.Uk=Lg;if(!C(this.el))this.el=hh;if(!C(this.ll))this.ll=yh;if(!C(this.sl))this.sl=zh;if(!C(this.zl))this.zl=Kh;if(!C(this.Kl))this.Kl=Nh;if(!C(this.Ml))this.Ml=Oh;if(a){this.Jh(a.agent);this.Uh(a.city);this.bi(a.country);this.vi(a.formattedAddress);this.Ji(a.housename);xa(this,a[tb]);this.mailClass=a.mailClass;this.Zi(a.neighborhood);this.ij(a.pobox);this.qj(a.postcode);
this.aa(a.primary);this.zj(a.region);this.rel=a.rel;this.Lj(a.street);this.Nj(a.subregion);this.usage=a.usage}else{this.gd$agent=E.util.mutateTo(this.gd$agent,this.hk);this.gd$city=E.util.mutateTo(this.gd$city,this.pk);this.gd$country=E.util.mutateTo(this.gd$country,this.uk);this.gd$formattedAddress=E.util.mutateTo(this.gd$formattedAddress,this.Jk);this.gd$housename=E.util.mutateTo(this.gd$housename,this.Uk);xa(this,this[tb]);this.mailClass=this.mailClass;this.gd$neighborhood=E.util.mutateTo(this.gd$neighborhood,
this.el);this.gd$pobox=E.util.mutateTo(this.gd$pobox,this.ll);this.gd$postcode=E.util.mutateTo(this.gd$postcode,this.sl);this.primary=this.primary;this.gd$region=E.util.mutateTo(this.gd$region,this.zl);this.rel=this.rel;this.gd$street=E.util.mutateTo(this.gd$street,this.Kl);this.gd$subregion=E.util.mutateTo(this.gd$subregion,this.Ml);this.usage=this.usage}};D("google.gdata.StructuredPostalAddress",O);O[t].Cm=function(){return this.gd$agent};
D("google.gdata.StructuredPostalAddress.prototype.getAgent",O[t].Cm);O[t].Jh=function(a){if(a&&a[u]===m)a=new this.hk(a);this.gd$agent=a};D("google.gdata.StructuredPostalAddress.prototype.setAgent",O[t].Jh);O[t].Xm=function(){return this.gd$city};D("google.gdata.StructuredPostalAddress.prototype.getCity",O[t].Xm);O[t].Uh=function(a){if(a&&a[u]===m)a=new this.pk(a);this.gd$city=a};D("google.gdata.StructuredPostalAddress.prototype.setCity",O[t].Uh);O[t].pn=function(){return this.gd$country};
D("google.gdata.StructuredPostalAddress.prototype.getCountry",O[t].pn);O[t].bi=function(a){if(a&&a[u]===m)a=new this.uk(a);this.gd$country=a};D("google.gdata.StructuredPostalAddress.prototype.setCountry",O[t].bi);O[t].Un=function(){return this.gd$formattedAddress};D("google.gdata.StructuredPostalAddress.prototype.getFormattedAddress",O[t].Un);O[t].vi=function(a){if(a&&a[u]===m)a=new this.Jk(a);this.gd$formattedAddress=a};D("google.gdata.StructuredPostalAddress.prototype.setFormattedAddress",O[t].vi);
O[t].mo=function(){return this.gd$housename};D("google.gdata.StructuredPostalAddress.prototype.getHousename",O[t].mo);O[t].Ji=function(a){if(a&&a[u]===m)a=new this.Uk(a);this.gd$housename=a};D("google.gdata.StructuredPostalAddress.prototype.setHousename",O[t].Ji);O[t].I=function(){return this[tb]};D("google.gdata.StructuredPostalAddress.prototype.getLabel",O[t].I);O[t].J=function(a){xa(this,a)};D("google.gdata.StructuredPostalAddress.prototype.setLabel",O[t].J);O[t].Mo=function(){return this.mailClass};
D("google.gdata.StructuredPostalAddress.prototype.getMailClass",O[t].Mo);O[t].Dr=function(a){this.mailClass=a};D("google.gdata.StructuredPostalAddress.prototype.setMailClass",O[t].Dr);var ri=E.namespace.GD+"#both";D("google.gdata.StructuredPostalAddress.MAILCLASS_BOTH",ri);var si=E.namespace.GD+"#letters";D("google.gdata.StructuredPostalAddress.MAILCLASS_LETTERS",si);var ti=E.namespace.GD+"#neither";D("google.gdata.StructuredPostalAddress.MAILCLASS_NEITHER",ti);var ui=E.namespace.GD+"#parcels";
D("google.gdata.StructuredPostalAddress.MAILCLASS_PARCELS",ui);O[t].ap=function(){return this.gd$neighborhood};D("google.gdata.StructuredPostalAddress.prototype.getNeighborhood",O[t].ap);O[t].Zi=function(a){if(a&&a[u]===m)a=new this.el(a);this.gd$neighborhood=a};D("google.gdata.StructuredPostalAddress.prototype.setNeighborhood",O[t].Zi);O[t].pp=function(){return this.gd$pobox};D("google.gdata.StructuredPostalAddress.prototype.getPobox",O[t].pp);
O[t].ij=function(a){if(a&&a[u]===m)a=new this.ll(a);this.gd$pobox=a};D("google.gdata.StructuredPostalAddress.prototype.setPobox",O[t].ij);O[t].Cp=function(){return this.gd$postcode};D("google.gdata.StructuredPostalAddress.prototype.getPostcode",O[t].Cp);O[t].qj=function(a){if(a&&a[u]===m)a=new this.sl(a);this.gd$postcode=a};D("google.gdata.StructuredPostalAddress.prototype.setPostcode",O[t].qj);O[t].va=function(){return this.primary===undefined?undefined:this.primary==="true"};
D("google.gdata.StructuredPostalAddress.prototype.getPrimary",O[t].va);O[t].aa=function(a){this.primary=a===undefined?undefined:i(a)};D("google.gdata.StructuredPostalAddress.prototype.setPrimary",O[t].aa);O[t].Rp=function(){return this.gd$region};D("google.gdata.StructuredPostalAddress.prototype.getRegion",O[t].Rp);O[t].zj=function(a){if(a&&a[u]===m)a=new this.zl(a);this.gd$region=a};D("google.gdata.StructuredPostalAddress.prototype.setRegion",O[t].zj);O[t].q=function(){return this.rel};
D("google.gdata.StructuredPostalAddress.prototype.getRel",O[t].q);O[t].p=function(a){this.rel=a};D("google.gdata.StructuredPostalAddress.prototype.setRel",O[t].p);var vi=E.namespace.GD+"#home";D("google.gdata.StructuredPostalAddress.REL_HOME",vi);var wi=E.namespace.GD+"#other";D("google.gdata.StructuredPostalAddress.REL_OTHER",wi);var xi=E.namespace.GD+"#work";D("google.gdata.StructuredPostalAddress.REL_WORK",xi);O[t].pq=function(){return this.gd$street};
D("google.gdata.StructuredPostalAddress.prototype.getStreet",O[t].pq);O[t].Lj=function(a){if(a&&a[u]===m)a=new this.Kl(a);this.gd$street=a};D("google.gdata.StructuredPostalAddress.prototype.setStreet",O[t].Lj);O[t].sq=function(){return this.gd$subregion};D("google.gdata.StructuredPostalAddress.prototype.getSubregion",O[t].sq);O[t].Nj=function(a){if(a&&a[u]===m)a=new this.Ml(a);this.gd$subregion=a};D("google.gdata.StructuredPostalAddress.prototype.setSubregion",O[t].Nj);O[t].Lq=function(){return this.usage};
D("google.gdata.StructuredPostalAddress.prototype.getUsage",O[t].Lq);O[t].fs=function(a){this.usage=a};D("google.gdata.StructuredPostalAddress.prototype.setUsage",O[t].fs);var yi=E.namespace.GD+"#general";D("google.gdata.StructuredPostalAddress.USAGE_GENERAL",yi);var zi=E.namespace.GD+"#local";D("google.gdata.StructuredPostalAddress.USAGE_LOCAL",zi);var Ai=function(a){if(!C(this.eb))this.eb=qi;if(a){this.bb(a.entryLink);this.Jj(a.specialized)}else{this.gd$entryLink=E.util.mutateTo(this.gd$entryLink,this.eb);this.specialized=this.specialized}};D("google.gdata.RecurrenceException",Ai);Ai[t].kb=function(){return this.gd$entryLink};D("google.gdata.RecurrenceException.prototype.getEntryLink",Ai[t].kb);Ai[t].bb=function(a){if(a&&a[u]===m)a=new this.eb(a);this.gd$entryLink=a};D("google.gdata.RecurrenceException.prototype.setEntryLink",Ai[t].bb);
Ai[t].mq=function(){return this.specialized===undefined?undefined:this.specialized==="true"};D("google.gdata.RecurrenceException.prototype.getSpecialized",Ai[t].mq);Ai[t].Jj=function(a){this.specialized=a===undefined?undefined:i(a)};D("google.gdata.RecurrenceException.prototype.setSpecialized",Ai[t].Jj);var P=function(a){if(!C(this.tb))this.tb=mi;if(!C(this.Kd))this.Kd=Bg;if(!C(this.Pd))this.Pd=Yh;if(!C(this.Sd))this.Sd=pi;if(!C(this.kg))this.kg=bi;if(!C(this.yl))this.yl=Jh;if(!C(this.lg))this.lg=Ai;if(!C(this.Bl))this.Bl=Lh;if(!C(this.Vl))this.Vl=Xh;if(!C(this.ee))this.ee=Ph;if(!C(this.he))this.he=Sh;J[z](this,a);if(a){this.wc(a.comments);this.Dc(a.eventStatus);this.Jc(a.locations);this.Lc(a.originalEvent);this.fj(a.participants);this.xj(a.recurrence);this.yj(a.recurrenceException);this.Bj(a.reminders);
this.Vj(a.times);this.fd(a.transparency);this.hd(a.visibility)}else{this.gd$comments=E.util.mutateTo(this.gd$comments,this.tb);this.gd$eventStatus=E.util.mutateTo(this.gd$eventStatus,this.Kd);if(this.gd$where)for(var d=this.gd$where,e=0;e<d[r];e++)this.gd$where[e]=E.util.mutateTo(d[e],this.Pd);else this.gd$where=[];this.gd$originalEvent=E.util.mutateTo(this.gd$originalEvent,this.Sd);if(this.gd$who){d=this.gd$who;for(e=0;e<d[r];e++)this.gd$who[e]=E.util.mutateTo(d[e],this.kg)}else this.gd$who=[];this.gd$recurrence=
E.util.mutateTo(this.gd$recurrence,this.yl);if(this.gd$recurrenceException){d=this.gd$recurrenceException;for(e=0;e<d[r];e++)this.gd$recurrenceException[e]=E.util.mutateTo(d[e],this.lg)}else this.gd$recurrenceException=[];if(this.gd$reminder){d=this.gd$reminder;for(e=0;e<d[r];e++)this.gd$reminder[e]=E.util.mutateTo(d[e],this.Bl)}else this.gd$reminder=[];if(this.gd$when){d=this.gd$when;for(e=0;e<d[r];e++)this.gd$when[e]=E.util.mutateTo(d[e],this.Vl)}else this.gd$when=[];this.gd$transparency=E.util.mutateTo(this.gd$transparency,
this.ee);this.gd$visibility=E.util.mutateTo(this.gd$visibility,this.he)}var h=["app$control","rights","app$edited"];for(e=0;e<h[r];e++){var j=h[e];j in this&&!C(this[j])&&delete this[j]}};D("google.gdata.EventEntry",P);P.e(J);P[t].f=E.namespace.GD;D("google.gdata.EventEntry.prototype.xmlns$gd",P[t].f);P[t].ha=E.opensearch.namespace.OPENSEARCH;D("google.gdata.EventEntry.prototype.xmlns$openSearch",P[t].ha);P[t].pe=function(){return this.gd$comments};
D("google.gdata.EventEntry.prototype.getComments",P[t].pe);P[t].wc=function(a){if(a&&a[u]===m)a=new this.tb(a);this.gd$comments=a};D("google.gdata.EventEntry.prototype.setComments",P[t].wc);P[t].Ae=function(){return this.gd$eventStatus};D("google.gdata.EventEntry.prototype.getEventStatus",P[t].Ae);P[t].Dc=function(a){if(a&&a[u]===m)a=new this.Kd(a);this.gd$eventStatus=a};D("google.gdata.EventEntry.prototype.setEventStatus",P[t].Dc);P[t].Ie=function(){return this.gd$where};
D("google.gdata.EventEntry.prototype.getLocations",P[t].Ie);P[t].Jc=function(a){this.gd$where=[];if(a)for(var d=0;d<a[r];d++)this.$b(a[d])};D("google.gdata.EventEntry.prototype.setLocations",P[t].Jc);P[t].$b=function(a){if(a[u]===m)a=new this.Pd(a);this.gd$where[q](a)};D("google.gdata.EventEntry.prototype.addLocation",P[t].$b);P[t].Le=function(){return this.gd$originalEvent};D("google.gdata.EventEntry.prototype.getOriginalEvent",P[t].Le);
P[t].Lc=function(a){if(a&&a[u]===m)a=new this.Sd(a);this.gd$originalEvent=a};D("google.gdata.EventEntry.prototype.setOriginalEvent",P[t].Lc);P[t].np=function(){return this.gd$who};D("google.gdata.EventEntry.prototype.getParticipants",P[t].np);P[t].fj=function(a){this.gd$who=[];if(a)for(var d=0;d<a[r];d++)this.ah(a[d])};D("google.gdata.EventEntry.prototype.setParticipants",P[t].fj);P[t].ah=function(a){if(a[u]===m)a=new this.kg(a);this.gd$who[q](a)};
D("google.gdata.EventEntry.prototype.addParticipant",P[t].ah);P[t].Np=function(){return this.gd$recurrence};D("google.gdata.EventEntry.prototype.getRecurrence",P[t].Np);P[t].xj=function(a){if(a&&a[u]===m)a=new this.yl(a);this.gd$recurrence=a};D("google.gdata.EventEntry.prototype.setRecurrence",P[t].xj);P[t].Op=function(){return this.gd$recurrenceException};D("google.gdata.EventEntry.prototype.getRecurrenceException",P[t].Op);P[t].yj=function(a){this.gd$recurrenceException=[];if(a)for(var d=0;d<a[r];d++)this.eh(a[d])};
D("google.gdata.EventEntry.prototype.setRecurrenceException",P[t].yj);P[t].eh=function(a){if(a[u]===m)a=new this.lg(a);this.gd$recurrenceException[q](a)};D("google.gdata.EventEntry.prototype.addRecurrenceException",P[t].eh);P[t].Up=function(){return this.gd$reminder};D("google.gdata.EventEntry.prototype.getReminders",P[t].Up);P[t].Bj=function(a){this.gd$reminder=[];if(a)for(var d=0;d<a[r];d++)this.dc(a[d])};D("google.gdata.EventEntry.prototype.setReminders",P[t].Bj);
P[t].dc=function(a){if(a[u]===m)a=new this.Bl(a);this.gd$reminder[q](a)};D("google.gdata.EventEntry.prototype.addReminder",P[t].dc);P[t].Cq=function(){return this.gd$when};D("google.gdata.EventEntry.prototype.getTimes",P[t].Cq);P[t].Vj=function(a){this.gd$when=[];if(a)for(var d=0;d<a[r];d++)this.fh(a[d])};D("google.gdata.EventEntry.prototype.setTimes",P[t].Vj);P[t].fh=function(a){if(a[u]===m)a=new this.Vl(a);this.gd$when[q](a)};D("google.gdata.EventEntry.prototype.addTime",P[t].fh);P[t].rf=function(){return this.gd$transparency};
D("google.gdata.EventEntry.prototype.getTransparency",P[t].rf);P[t].fd=function(a){if(a&&a[u]===m)a=new this.ee(a);this.gd$transparency=a};D("google.gdata.EventEntry.prototype.setTransparency",P[t].fd);P[t].uf=function(){return this.gd$visibility};D("google.gdata.EventEntry.prototype.getVisibility",P[t].uf);P[t].hd=function(a){if(a&&a[u]===m)a=new this.he(a);this.gd$visibility=a};D("google.gdata.EventEntry.prototype.setVisibility",P[t].hd);var Bi=function(a){if(!C(this.m))this.m=P;K[z](this,a);for(var d=["xml$base","rights","logo"],e=0;e<d[r];e++){var h=d[e];h in this&&!C(this[h])&&delete this[h]}};D("google.gdata.EventFeed",Bi);Bi.e(K);Bi[t].f=E.namespace.GD;D("google.gdata.EventFeed.prototype.xmlns$gd",Bi[t].f);E.params={};E.params.ALT="alt";E.params.AUTHOR="author";E.params.MAX_RESULTS="max-results";E.params.PRETTYPRINT="prettyprint";E.params.PUBLISHED_MAX="published-max";E.params.PUBLISHED_MIN="published-min";E.params.Q="q";E.params.START_INDEX="start-index";E.params.UPDATED_MAX="updated-max";E.params.UPDATED_MIN="updated-min";mi[t].xg=function(){return Jg};D("google.gdata.Comments.prototype.getFeedLinkClass",mi[t].xg);J[t].mn=function(){return bg};D("google.gdata.Entry.prototype.getControlClass",J[t].mn);P[t].kc=function(){return mi};D("google.gdata.EventEntry.prototype.getCommentsClass",P[t].kc);P[t].pc=function(){return bi};D("google.gdata.EventEntry.prototype.getWhoClass",P[t].pc);P[t].Ag=function(){return Ai};D("google.gdata.EventEntry.prototype.getRecurrenceExceptionClass",P[t].Ag);Bi[t].da=function(){return P};
K[t].da=function(){return J};qi[t].da=function(){return L};L[t].kc=function(){return mi};D("google.gdata.RecurrenceExceptionEntry.prototype.getCommentsClass",L[t].kc);L[t].pc=function(){return bi};D("google.gdata.RecurrenceExceptionEntry.prototype.getWhoClass",L[t].pc);

E.contacts={};E.contacts.namespace={};E.contacts.namespace.GCONTACT="http://schemas.google.com/contact/2008";var Tk=function(a){Zg[z](this,a);for(var d=["label"],e=0;e<d[r];e++){var h=d[e];h in this&&!C(this[h])&&delete this[h]}};D("google.gdata.contacts.ContactGroupKind",Tk);Tk.e(Zg);var Uk=E.contacts.namespace.GCONTACT+"#group";D("google.gdata.contacts.ContactGroupKind.TERM_GROUP",Uk);var Vk=function(a){Zg[z](this,a);for(var d=["label"],e=0;e<d[r];e++){var h=d[e];h in this&&!C(this[h])&&delete this[h]}};D("google.gdata.contacts.ContactKind",Vk);Vk.e(Zg);var Wk=E.contacts.namespace.GCONTACT+"#contact";D("google.gdata.contacts.ContactKind.TERM_CONTACT",Wk);var Xk=function(a){bh[z](this,a);for(var d=["hreflang","xml$lang"],e=0;e<d[r];e++){var h=d[e];h in this&&!C(this[h])&&delete this[h]}};D("google.gdata.contacts.ContactLink",Xk);Xk.e(bh);D("google.gdata.contacts.ContactLink.REL_CONTACT_PHOTO","http://schemas.google.com/contacts/2008/rel#photo");D("google.gdata.contacts.ContactLink.REL_EDIT_CONTACT_PHOTO","http://schemas.google.com/contacts/2008/rel#edit-photo");D("google.gdata.contacts.ContactLink.TYPE_IMAGE","image/*");var Yk=function(a){if(a){this.la(a.deleted);va(this,a[A])}else{this.deleted=this.deleted;va(this,this[A])}};D("google.gdata.contacts.GroupMembershipInfo",Yk);Yk[t].Ha=function(){return this.deleted===undefined?undefined:this.deleted==="true"};D("google.gdata.contacts.GroupMembershipInfo.prototype.getDeleted",Yk[t].Ha);Yk[t].la=function(a){this.deleted=a===undefined?undefined:i(a)};D("google.gdata.contacts.GroupMembershipInfo.prototype.setDeleted",Yk[t].la);Yk[t].T=function(){return this[A]};
D("google.gdata.contacts.GroupMembershipInfo.prototype.getHref",Yk[t].T);Yk[t].N=function(a){va(this,a)};D("google.gdata.contacts.GroupMembershipInfo.prototype.setHref",Yk[t].N);var Zk=function(a){Zg[z](this,a);for(var d=["label"],e=0;e<d[r];e++){var h=d[e];h in this&&!C(this[h])&&delete this[h]}};D("google.gdata.contacts.ProfileKind",Zk);Zk.e(Zg);var $k=E.contacts.namespace.GCONTACT+"#profile";D("google.gdata.contacts.ProfileKind.TERM_PROFILE",$k);var al=function(a){this.id=a?a.id:this.id};D("google.gdata.contacts.SystemGroup",al);al[t].Ia=function(){return this.id};D("google.gdata.contacts.SystemGroup.prototype.getId",al[t].Ia);al[t].Ba=function(a){this.id=a};D("google.gdata.contacts.SystemGroup.prototype.setId",al[t].Ba);var bl=function(a){if(!C(this.Qa))this.Qa=vg;if(!C(this.ub))this.ub=Fg;if(!C(this.Sl))this.Sl=al;J[z](this,a);if(a){this.la(a.deleted);this.cb(a.extendedProperties);this.Rj(a.systemGroup)}else{this.gd$deleted=E.util.mutateTo(this.gd$deleted,this.Qa);if(this.gd$extendedProperty)for(var d=this.gd$extendedProperty,e=0;e<d[r];e++)this.gd$extendedProperty[e]=E.util.mutateTo(d[e],this.ub);else this.gd$extendedProperty=[];this.gContact$systemGroup=E.util.mutateTo(this.gContact$systemGroup,this.Sl)}var h=
["published","app$control","summary","rights"];for(e=0;e<h[r];e++){var j=h[e];j in this&&!C(this[j])&&delete this[j]}};D("google.gdata.contacts.ContactGroupEntry",bl);bl.e(J);bl[t].Ya=E.contacts.namespace.GCONTACT;D("google.gdata.contacts.ContactGroupEntry.prototype.xmlns$gContact",bl[t].Ya);bl[t].f=E.namespace.GD;D("google.gdata.contacts.ContactGroupEntry.prototype.xmlns$gd",bl[t].f);bl[t].Ha=function(){return this.gd$deleted};D("google.gdata.contacts.ContactGroupEntry.prototype.getDeleted",bl[t].Ha);
bl[t].la=function(a){if(a&&a[u]===m)a=new this.Qa(a);this.gd$deleted=a};D("google.gdata.contacts.ContactGroupEntry.prototype.setDeleted",bl[t].la);bl[t].Ab=function(){return this.gd$extendedProperty};D("google.gdata.contacts.ContactGroupEntry.prototype.getExtendedProperties",bl[t].Ab);bl[t].cb=function(a){this.gd$extendedProperty=[];if(a)for(var d=0;d<a[r];d++)this.$a(a[d])};D("google.gdata.contacts.ContactGroupEntry.prototype.setExtendedProperties",bl[t].cb);
bl[t].$a=function(a){if(a[u]===m)a=new this.ub(a);this.gd$extendedProperty[q](a)};D("google.gdata.contacts.ContactGroupEntry.prototype.addExtendedProperty",bl[t].$a);bl[t].wq=function(){return this.gContact$systemGroup};D("google.gdata.contacts.ContactGroupEntry.prototype.getSystemGroup",bl[t].wq);bl[t].Rj=function(a){if(a&&a[u]===m)a=new this.Sl(a);this.gContact$systemGroup=a};D("google.gdata.contacts.ContactGroupEntry.prototype.setSystemGroup",bl[t].Rj);var cl=function(a){if(!C(this.m))this.m=bl;K[z](this,a);for(var d=["subtitle","xml$base","rights","logo"],e=0;e<d[r];e++){var h=d[e];h in this&&!C(this[h])&&delete this[h]}};D("google.gdata.contacts.ContactGroupFeed",cl);cl.e(K);cl[t].Ya=E.contacts.namespace.GCONTACT;D("google.gdata.contacts.ContactGroupFeed.prototype.xmlns$gContact",cl[t].Ya);cl[t].f=E.namespace.GD;D("google.gdata.contacts.ContactGroupFeed.prototype.xmlns$gd",cl[t].f);cl[t].P=function(){return this.g(ch,"application/atom+xml")};
D("google.gdata.contacts.ContactGroupFeed.prototype.getFeedBatchLink",cl[t].P);cl[t].t=function(){return this.g("next","application/atom+xml")};D("google.gdata.contacts.ContactGroupFeed.prototype.getNextLink",cl[t].t);cl[t].F=function(){return this.g("previous","application/atom+xml")};D("google.gdata.contacts.ContactGroupFeed.prototype.getPreviousLink",cl[t].F);var dl=function(a){if(!C(this.Ck))this.Ck=wg;if(!C(this.ub))this.ub=Fg;if(!C(this.Vk))this.Vk=Ng;if(!C(this.n))this.n=Xk;if(!C(this.hl))this.hl=lh;if(!C(this.kl))this.kl=ph;if(!C(this.rl))this.rl=Ah;J[z](this,a);if(a){this.li(a.emailAddresses);this.cb(a.extendedProperties);this.Ki(a.imAddresses);this.cj(a.organizations);this.hj(a.phoneNumbers);this.pj(a.postalAddresses)}else{if(this.gd$email)for(var d=this.gd$email,e=0;e<d[r];e++)this.gd$email[e]=E.util.mutateTo(d[e],this.Ck);else this.gd$email=[];
if(this.gd$extendedProperty){d=this.gd$extendedProperty;for(e=0;e<d[r];e++)this.gd$extendedProperty[e]=E.util.mutateTo(d[e],this.ub)}else this.gd$extendedProperty=[];if(this.gd$im){d=this.gd$im;for(e=0;e<d[r];e++)this.gd$im[e]=E.util.mutateTo(d[e],this.Vk)}else this.gd$im=[];if(this.gd$organization){d=this.gd$organization;for(e=0;e<d[r];e++)this.gd$organization[e]=E.util.mutateTo(d[e],this.hl)}else this.gd$organization=[];if(this.gd$phoneNumber){d=this.gd$phoneNumber;for(e=0;e<d[r];e++)this.gd$phoneNumber[e]=
E.util.mutateTo(d[e],this.kl)}else this.gd$phoneNumber=[];if(this.gd$postalAddress){d=this.gd$postalAddress;for(e=0;e<d[r];e++)this.gd$postalAddress[e]=E.util.mutateTo(d[e],this.rl)}else this.gd$postalAddress=[]}var h=["published","app$control","summary","rights"];for(e=0;e<h[r];e++){var j=h[e];j in this&&!C(this[j])&&delete this[j]}};D("google.gdata.contacts.PersonEntry",dl);dl.e(J);dl[t].f=E.namespace.GD;D("google.gdata.contacts.PersonEntry.prototype.xmlns$gd",dl[t].f);dl[t].An=function(){return this.gd$email};
D("google.gdata.contacts.PersonEntry.prototype.getEmailAddresses",dl[t].An);dl[t].li=function(a){this.gd$email=[];if(a)for(var d=0;d<a[r];d++)this.Ug(a[d])};D("google.gdata.contacts.PersonEntry.prototype.setEmailAddresses",dl[t].li);dl[t].Ug=function(a){if(a[u]===m)a=new this.Ck(a);this.gd$email[q](a)};D("google.gdata.contacts.PersonEntry.prototype.addEmailAddress",dl[t].Ug);dl[t].Ab=function(){return this.gd$extendedProperty};
D("google.gdata.contacts.PersonEntry.prototype.getExtendedProperties",dl[t].Ab);dl[t].cb=function(a){this.gd$extendedProperty=[];if(a)for(var d=0;d<a[r];d++)this.$a(a[d])};D("google.gdata.contacts.PersonEntry.prototype.setExtendedProperties",dl[t].cb);dl[t].$a=function(a){if(a[u]===m)a=new this.ub(a);this.gd$extendedProperty[q](a)};D("google.gdata.contacts.PersonEntry.prototype.addExtendedProperty",dl[t].$a);dl[t].po=function(){return this.gd$im};
D("google.gdata.contacts.PersonEntry.prototype.getImAddresses",dl[t].po);dl[t].Ki=function(a){this.gd$im=[];if(a)for(var d=0;d<a[r];d++)this.Zg(a[d])};D("google.gdata.contacts.PersonEntry.prototype.setImAddresses",dl[t].Ki);dl[t].Zg=function(a){if(a[u]===m)a=new this.Vk(a);this.gd$im[q](a)};D("google.gdata.contacts.PersonEntry.prototype.addImAddress",dl[t].Zg);dl[t].hp=function(){return this.gd$organization};D("google.gdata.contacts.PersonEntry.prototype.getOrganizations",dl[t].hp);
dl[t].cj=function(a){this.gd$organization=[];if(a)for(var d=0;d<a[r];d++)this.$g(a[d])};D("google.gdata.contacts.PersonEntry.prototype.setOrganizations",dl[t].cj);dl[t].$g=function(a){if(a[u]===m)a=new this.hl(a);this.gd$organization[q](a)};D("google.gdata.contacts.PersonEntry.prototype.addOrganization",dl[t].$g);dl[t].op=function(){return this.gd$phoneNumber};D("google.gdata.contacts.PersonEntry.prototype.getPhoneNumbers",dl[t].op);dl[t].hj=function(a){this.gd$phoneNumber=[];if(a)for(var d=0;d<a[r];d++)this.bh(a[d])};
D("google.gdata.contacts.PersonEntry.prototype.setPhoneNumbers",dl[t].hj);dl[t].bh=function(a){if(a[u]===m)a=new this.kl(a);this.gd$phoneNumber[q](a)};D("google.gdata.contacts.PersonEntry.prototype.addPhoneNumber",dl[t].bh);dl[t].Bp=function(){return this.gd$postalAddress};D("google.gdata.contacts.PersonEntry.prototype.getPostalAddresses",dl[t].Bp);dl[t].pj=function(a){this.gd$postalAddress=[];if(a)for(var d=0;d<a[r];d++)this.dh(a[d])};
D("google.gdata.contacts.PersonEntry.prototype.setPostalAddresses",dl[t].pj);dl[t].dh=function(a){if(a[u]===m)a=new this.rl(a);this.gd$postalAddress[q](a)};D("google.gdata.contacts.PersonEntry.prototype.addPostalAddress",dl[t].dh);dl[t].dn=function(){return this.g("http://schemas.google.com/contacts/2008/rel#edit-photo","image/*")};D("google.gdata.contacts.PersonEntry.prototype.getContactEditPhotoLink",dl[t].dn);
dl[t].jn=function(){return this.g("http://schemas.google.com/contacts/2008/rel#photo","image/*")};D("google.gdata.contacts.PersonEntry.prototype.getContactPhotoLink",dl[t].jn);var el=function(a){if(!C(this.Qa))this.Qa=vg;if(!C(this.Pk))this.Pk=Yk;dl[z](this,a);if(a){this.la(a.deleted);this.Ei(a.groupMembershipInfos)}else{this.gd$deleted=E.util.mutateTo(this.gd$deleted,this.Qa);if(this.gContact$groupMembershipInfo)for(var d=this.gContact$groupMembershipInfo,e=0;e<d[r];e++)this.gContact$groupMembershipInfo[e]=E.util.mutateTo(d[e],this.Pk);else this.gContact$groupMembershipInfo=[]}};D("google.gdata.contacts.ContactEntry",el);el.e(dl);el[t].Ya=E.contacts.namespace.GCONTACT;
D("google.gdata.contacts.ContactEntry.prototype.xmlns$gContact",el[t].Ya);el[t].Ha=function(){return this.gd$deleted};D("google.gdata.contacts.ContactEntry.prototype.getDeleted",el[t].Ha);el[t].la=function(a){if(a&&a[u]===m)a=new this.Qa(a);this.gd$deleted=a};D("google.gdata.contacts.ContactEntry.prototype.setDeleted",el[t].la);el[t].fo=function(){return this.gContact$groupMembershipInfo};D("google.gdata.contacts.ContactEntry.prototype.getGroupMembershipInfos",el[t].fo);
el[t].Ei=function(a){this.gContact$groupMembershipInfo=[];if(a)for(var d=0;d<a[r];d++)this.Yg(a[d])};D("google.gdata.contacts.ContactEntry.prototype.setGroupMembershipInfos",el[t].Ei);el[t].Yg=function(a){if(a[u]===m)a=new this.Pk(a);this.gContact$groupMembershipInfo[q](a)};D("google.gdata.contacts.ContactEntry.prototype.addGroupMembershipInfo",el[t].Yg);var fl=function(a){if(!C(this.m))this.m=el;if(!C(this.n))this.n=Xk;K[z](this,a);for(var d=["subtitle","xml$base","rights","logo"],e=0;e<d[r];e++){var h=d[e];h in this&&!C(this[h])&&delete this[h]}};D("google.gdata.contacts.ContactFeed",fl);fl.e(K);fl[t].Ya=E.contacts.namespace.GCONTACT;D("google.gdata.contacts.ContactFeed.prototype.xmlns$gContact",fl[t].Ya);fl[t].f=E.namespace.GD;D("google.gdata.contacts.ContactFeed.prototype.xmlns$gd",fl[t].f);fl[t].P=function(){return this.g(ch,"application/atom+xml")};
D("google.gdata.contacts.ContactFeed.prototype.getFeedBatchLink",fl[t].P);fl[t].t=function(){return this.g("next","application/atom+xml")};D("google.gdata.contacts.ContactFeed.prototype.getNextLink",fl[t].t);fl[t].F=function(){return this.g("previous","application/atom+xml")};D("google.gdata.contacts.ContactFeed.prototype.getPreviousLink",fl[t].F);E.contacts.params={};E.contacts.params.DOMAIN_NAME="domain-name";E.contacts.params.GROUP="group";E.contacts.params.ORDERBY="orderby";E.contacts.params.SHOWDELETED="showdeleted";E.contacts.params.SORTORDER="sortorder";E.contacts.params.START_KEY="start-key";E.contacts.params.USER_NAME="user-name";var gl=function(a){Hf[z](this,a);this.v(E.contacts.params.ORDERBY,{defaultValue:"none"});this.v(E.contacts.params.SHOWDELETED,{defaultValue:g});this.v(E.contacts.params.SORTORDER,{defaultValue:"none"});this.v(E.params.START_INDEX,{defaultValue:1})};D("google.gdata.contacts.ContactQuery",gl);gl.e(Hf);gl[t].ur=function(a){this.d(E.contacts.params.GROUP,a)};D("google.gdata.contacts.ContactQuery.prototype.setGroup",gl[t].ur);gl[t].eo=function(){return this.c(E.contacts.params.GROUP)};
D("google.gdata.contacts.ContactQuery.prototype.getGroup",gl[t].eo);gl[t].k=function(a){if(typeof a=="string")a=k(a);this.d(E.params.MAX_RESULTS,a)};D("google.gdata.contacts.ContactQuery.prototype.setMaxResults",gl[t].k);gl[t].j=function(){return this.c(E.params.MAX_RESULTS)};D("google.gdata.contacts.ContactQuery.prototype.getMaxResults",gl[t].j);D("google.gdata.contacts.ContactQuery.ORDERBY_EDITED","edited");D("google.gdata.contacts.ContactQuery.ORDERBY_LAST_MODIFIED","lastmodified");
D("google.gdata.contacts.ContactQuery.ORDERBY_NONE","none");gl[t].Lb=function(a){this.d(E.contacts.params.ORDERBY,a)};D("google.gdata.contacts.ContactQuery.prototype.setOrderBy",gl[t].Lb);gl[t].Bb=function(){return this.c(E.contacts.params.ORDERBY)};D("google.gdata.contacts.ContactQuery.prototype.getOrderBy",gl[t].Bb);gl[t].Ob=function(a){if(typeof a=="string")a=a==="true";this.d(E.contacts.params.SHOWDELETED,a)};D("google.gdata.contacts.ContactQuery.prototype.setShowDeleted",gl[t].Ob);gl[t].Fb=function(){return this.c(E.contacts.params.SHOWDELETED)};
D("google.gdata.contacts.ContactQuery.prototype.getShowDeleted",gl[t].Fb);D("google.gdata.contacts.ContactQuery.SORTORDER_ASCENDING","ascending");D("google.gdata.contacts.ContactQuery.SORTORDER_DESCENDING","descending");D("google.gdata.contacts.ContactQuery.SORTORDER_NONE","none");gl[t].Lf=function(a){this.d(E.contacts.params.SORTORDER,a)};D("google.gdata.contacts.ContactQuery.prototype.setSortOrder",gl[t].Lf);gl[t].hf=function(){return this.c(E.contacts.params.SORTORDER)};
D("google.gdata.contacts.ContactQuery.prototype.getSortOrder",gl[t].hf);gl[t].h=function(a){if(typeof a=="string")a=k(a);this.d(E.params.START_INDEX,a)};D("google.gdata.contacts.ContactQuery.prototype.setStartIndex",gl[t].h);gl[t].i=function(){return this.c(E.params.START_INDEX)};D("google.gdata.contacts.ContactQuery.prototype.getStartIndex",gl[t].i);gl[t].A=function(a){if(typeof a=="string")a=G(a);this.d(E.params.UPDATED_MAX,a)};D("google.gdata.contacts.ContactQuery.prototype.setUpdatedMax",gl[t].A);
gl[t].w=function(){return this.c(E.params.UPDATED_MAX)};D("google.gdata.contacts.ContactQuery.prototype.getUpdatedMax",gl[t].w);gl[t].B=function(a){if(typeof a=="string")a=G(a);this.d(E.params.UPDATED_MIN,a)};D("google.gdata.contacts.ContactQuery.prototype.setUpdatedMin",gl[t].B);gl[t].z=function(){return this.c(E.params.UPDATED_MIN)};D("google.gdata.contacts.ContactQuery.prototype.getUpdatedMin",gl[t].z);var hl=function(a){Ff[z](this,"cp",a)};D("google.gdata.contacts.ContactsService",hl);hl.e(Ff);D("google.gdata.contacts.ContactsService.SERVICE_NAME","cp");hl[t].fn=function(a,d,e){return this.M(a,d,e,fl)};D("google.gdata.contacts.ContactsService.prototype.getContactFeed",hl[t].fn);hl[t].hn=function(a,d,e){return this.M(a,d,e,cl)};D("google.gdata.contacts.ContactsService.prototype.getContactGroupFeed",hl[t].hn);hl[t].en=function(a,d,e){return this.O(a,d,e,el)};
D("google.gdata.contacts.ContactsService.prototype.getContactEntry",hl[t].en);hl[t].gn=function(a,d,e){return this.O(a,d,e,bl)};D("google.gdata.contacts.ContactsService.prototype.getContactGroupEntry",hl[t].gn);


google.loader.loaded({"module":"gdata","version":"1.10","components":["app","atom","default","opensearch","mediarss","core","gdata","contacts"]});
google.loader.eval.gdata = function() {eval(arguments[0]);};if (google.loader.eval.scripts && google.loader.eval.scripts['gdata']) {(function() {var scripts = google.loader.eval.scripts['gdata'];for (var i = 0; i < scripts.length; i++) {google.loader.eval.gdata(scripts[i]);}})();google.loader.eval.scripts['gdata'] = null;}})();
var RecaptchaTemplates={};RecaptchaTemplates.VertHtml='<table id="recaptcha_table" class="recaptchatable" > <tr> <td colspan="6" class=\'recaptcha_r1_c1\'></td> </tr> <tr> <td class=\'recaptcha_r2_c1\'></td> <td colspan="4" class=\'recaptcha_image_cell\'><div id="recaptcha_image"></div></td> <td class=\'recaptcha_r2_c2\'></td> </tr> <tr> <td rowspan="6" class=\'recaptcha_r3_c1\'></td> <td colspan="4" class=\'recaptcha_r3_c2\'></td> <td rowspan="6" class=\'recaptcha_r3_c3\'></td> </tr> <tr> <td rowspan="3" class=\'recaptcha_r4_c1\' height="49"> <div class="recaptcha_input_area"> <label for="recaptcha_response_field" class="recaptcha_input_area_text"><span id="recaptcha_instructions_image" class="recaptcha_only_if_image recaptcha_only_if_no_incorrect_sol"></span><span id="recaptcha_instructions_audio" class="recaptcha_only_if_no_incorrect_sol recaptcha_only_if_audio"></span><span id="recaptcha_instructions_error" class="recaptcha_only_if_incorrect_sol"></span></label><br/> <input name="recaptcha_response_field" id="recaptcha_response_field" type="text" /> </div> </td> <td rowspan="4" class=\'recaptcha_r4_c2\'></td> <td><a id=\'recaptcha_reload_btn\'><img id=\'recaptcha_reload\' width="25" height="17" /></a></td> <td rowspan="4" class=\'recaptcha_r4_c4\'></td> </tr> <tr> <td><a id=\'recaptcha_switch_audio_btn\' class="recaptcha_only_if_image"><img id=\'recaptcha_switch_audio\' width="25" height="16" alt="" /></a><a id=\'recaptcha_switch_img_btn\' class="recaptcha_only_if_audio"><img id=\'recaptcha_switch_img\' width="25" height="16" alt=""/></a></td> </tr> <tr> <td><a id=\'recaptcha_whatsthis_btn\'><img id=\'recaptcha_whatsthis\' width="25" height="16" /></a></td> </tr> <tr> <td class=\'recaptcha_r7_c1\'></td> <td class=\'recaptcha_r8_c1\'></td> </tr> </table> ';RecaptchaTemplates.CleanCss=".recaptchatable td img{display:block}.recaptchatable .recaptcha_image_cell center img{height:57px}.recaptchatable .recaptcha_image_cell center{height:57px}.recaptchatable .recaptcha_image_cell{background-color:white;height:57px;padding:7px!important}.recaptchatable,#recaptcha_area tr,#recaptcha_area td,#recaptcha_area th{margin:0!important;border:0!important;border-collapse:collapse!important;vertical-align:middle!important}.recaptchatable *{margin:0;padding:0;border:0;color:black;position:static;top:auto;left:auto;right:auto;bottom:auto;text-align:left!important}.recaptchatable #recaptcha_image{margin:auto;border:1px solid #dfdfdf!important}.recaptchatable a img{border:0}.recaptchatable a,.recaptchatable a:hover{outline:none;border:0!important;padding:0!important;text-decoration:none;color:blue;background:none!important;font-weight:normal}.recaptcha_input_area{position:relative!important;background:none!important}.recaptchatable label.recaptcha_input_area_text{border:1px solid #dfdfdf!important;margin:0!important;padding:0!important;position:static!important;top:auto!important;left:auto!important;right:auto!important;bottom:auto!important}.recaptcha_theme_red label.recaptcha_input_area_text,.recaptcha_theme_white label.recaptcha_input_area_text{color:black!important}.recaptcha_theme_blackglass label.recaptcha_input_area_text{color:white!important}.recaptchatable #recaptcha_response_field{font-size:11pt}.recaptcha_theme_blackglass #recaptcha_response_field,.recaptcha_theme_white #recaptcha_response_field{border:1px solid gray}.recaptcha_theme_red #recaptcha_response_field{border:1px solid #cca940}.recaptcha_audio_cant_hear_link{font-size:7pt;color:black}.recaptchatable{line-height:1em;border:1px solid #dfdfdf!important}.recaptcha_error_text{color:red}";RecaptchaTemplates.CleanHtml='<table id="recaptcha_table" class="recaptchatable"> <tr height="73"> <td class=\'recaptcha_image_cell\' width="302"><center><div id="recaptcha_image"></div></center></td> <td style="padding: 10px 7px 7px 7px;"> <a id=\'recaptcha_reload_btn\'><img id=\'recaptcha_reload\' width="25" height="18" alt="" /></a> <a id=\'recaptcha_switch_audio_btn\' class="recaptcha_only_if_image"><img id=\'recaptcha_switch_audio\' width="25" height="15" alt="" /></a><a id=\'recaptcha_switch_img_btn\' class="recaptcha_only_if_audio"><img id=\'recaptcha_switch_img\' width="25" height="15" alt=""/></a> <a id=\'recaptcha_whatsthis_btn\'><img id=\'recaptcha_whatsthis\' width="25" height="16" /></a> </td> <td style="padding: 18px 7px 18px 7px;"> <img id=\'recaptcha_logo\' alt="" width="71" height="36" /> </td> </tr> <tr> <td style="padding-left: 7px;"> <div class="recaptcha_input_area" style="padding-top: 2px; padding-bottom: 7px;"> <input style="border: 1px solid #3c3c3c; width: 302px;" name="recaptcha_response_field" id="recaptcha_response_field" type="text" /> </div> </td> <td></td> <td style="padding: 4px 7px 12px 7px;"> <img id="recaptcha_tagline" width="71" height="17" /> </td> </tr> </table> ';RecaptchaTemplates.ContextHtml='<table id="recaptcha_table" class="recaptchatable"> <tr> <td colspan="6" class=\'recaptcha_r1_c1\'></td> </tr> <tr> <td class=\'recaptcha_r2_c1\'></td> <td colspan="4" class=\'recaptcha_image_cell\'><div id="recaptcha_image"></div></td> <td class=\'recaptcha_r2_c2\'></td> </tr> <tr> <td rowspan="6" class=\'recaptcha_r3_c1\'></td> <td colspan="4" class=\'recaptcha_r3_c2\'></td> <td rowspan="6" class=\'recaptcha_r3_c3\'></td> </tr> <tr> <td rowspan="3" class=\'recaptcha_r4_c1\' height="49"> <div class="recaptcha_input_area"> <label for="recaptcha_response_field" class="recaptcha_input_area_text"><span id="recaptcha_instructions_context" class="recaptcha_only_if_image recaptcha_only_if_no_incorrect_sol"></span><span id="recaptcha_instructions_audio" class="recaptcha_only_if_no_incorrect_sol recaptcha_only_if_audio"></span><span id="recaptcha_instructions_error" class="recaptcha_only_if_incorrect_sol"></span></label><br/> <input name="recaptcha_response_field" id="recaptcha_response_field" type="text" /> </div> </td> <td rowspan="4" class=\'recaptcha_r4_c2\'></td> <td><a id=\'recaptcha_reload_btn\'><img id=\'recaptcha_reload\' width="25" height="17" /></a></td> <td rowspan="4" class=\'recaptcha_r4_c4\'></td> </tr> <tr> <td><a id=\'recaptcha_switch_audio_btn\' class="recaptcha_only_if_image"><img id=\'recaptcha_switch_audio\' width="25" height="16" alt="" /></a><a id=\'recaptcha_switch_img_btn\' class="recaptcha_only_if_audio"><img id=\'recaptcha_switch_img\' width="25" height="16" alt=""/></a></td> </tr> <tr> <td><a id=\'recaptcha_whatsthis_btn\'><img id=\'recaptcha_whatsthis\' width="25" height="16" /></a></td> </tr> <tr> <td class=\'recaptcha_r7_c1\'></td> <td class=\'recaptcha_r8_c1\'></td> </tr> </table> ';RecaptchaTemplates.VertCss=".recaptchatable td img{display:block}.recaptchatable .recaptcha_r1_c1{background:url(IMGROOT/sprite.png) 0 -63px no-repeat;width:318px;height:9px}.recaptchatable .recaptcha_r2_c1{background:url(IMGROOT/sprite.png) -18px 0 no-repeat;width:9px;height:57px}.recaptchatable .recaptcha_r2_c2{background:url(IMGROOT/sprite.png) -27px 0 no-repeat;width:9px;height:57px}.recaptchatable .recaptcha_r3_c1{background:url(IMGROOT/sprite.png) 0 0 no-repeat;width:9px;height:63px}.recaptchatable .recaptcha_r3_c2{background:url(IMGROOT/sprite.png) -18px -57px no-repeat;width:300px;height:6px}.recaptchatable .recaptcha_r3_c3{background:url(IMGROOT/sprite.png) -9px 0 no-repeat;width:9px;height:63px}.recaptchatable .recaptcha_r4_c1{background:url(IMGROOT/sprite.png) -43px 0 no-repeat;width:171px;height:49px}.recaptchatable .recaptcha_r4_c2{background:url(IMGROOT/sprite.png) -36px 0 no-repeat;width:7px;height:57px}.recaptchatable .recaptcha_r4_c4{background:url(IMGROOT/sprite.png) -214px 0 no-repeat;width:97px;height:57px}.recaptchatable .recaptcha_r7_c1{background:url(IMGROOT/sprite.png) -43px -49px no-repeat;width:171px;height:8px}.recaptchatable .recaptcha_r8_c1{background:url(IMGROOT/sprite.png) -43px -49px no-repeat;width:25px;height:8px}.recaptchatable .recaptcha_image_cell center img{height:57px}.recaptchatable .recaptcha_image_cell center{height:57px}.recaptchatable .recaptcha_image_cell{background-color:white;height:57px}#recaptcha_area,#recaptcha_table{width:318px!important}.recaptchatable,#recaptcha_area tr,#recaptcha_area td,#recaptcha_area th{margin:0!important;border:0!important;padding:0!important;border-collapse:collapse!important;vertical-align:middle!important}.recaptchatable *{margin:0;padding:0;border:0;font-family:helvetica,sans-serif;font-size:8pt;color:black;position:static;top:auto;left:auto;right:auto;bottom:auto;text-align:left!important}.recaptchatable #recaptcha_image{margin:auto}.recaptchatable img{border:0!important;margin:0!important;padding:0!important}.recaptchatable a,.recaptchatable a:hover{outline:none;border:0!important;padding:0!important;text-decoration:none;color:blue;background:none!important;font-weight:normal}.recaptcha_input_area{position:relative!important;width:146px!important;height:45px!important;margin-left:20px!important;margin-right:5px!important;margin-top:4px!important;background:none!important}.recaptchatable label.recaptcha_input_area_text{margin:0!important;padding:0!important;position:static!important;top:auto!important;left:auto!important;right:auto!important;bottom:auto!important;background:none!important;height:auto!important;width:auto!important}.recaptcha_theme_red label.recaptcha_input_area_text,.recaptcha_theme_white label.recaptcha_input_area_text{color:black!important}.recaptcha_theme_blackglass label.recaptcha_input_area_text{color:white!important}.recaptchatable #recaptcha_response_field{width:145px!important;position:absolute!important;bottom:7px!important;padding:0!important;margin:0!important;font-size:10pt}.recaptcha_theme_blackglass #recaptcha_response_field,.recaptcha_theme_white #recaptcha_response_field{border:1px solid gray}.recaptcha_theme_red #recaptcha_response_field{border:1px solid #cca940}.recaptcha_audio_cant_hear_link{font-size:7pt;color:black}.recaptchatable{line-height:1em}#recaptcha_instructions_error{color:red!important}";var RecaptchaStr_en={visual_challenge:"Get a visual challenge",audio_challenge:"Get an audio challenge",refresh_btn:"Get a new challenge",instructions_visual:"Type the two words:",instructions_context:"Type the words in the boxes:",instructions_audio:"Type what you hear:",help_btn:"Help",play_again:"Play sound again",cant_hear_this:"Download sound as MP3",incorrect_try_again:"Incorrect. Try again."},RecaptchaStr_de={visual_challenge:"Visuelle Aufgabe generieren",audio_challenge:"Audio-Aufgabe generieren",
refresh_btn:"Neue Aufgabe generieren",instructions_visual:"Gib die 2 W\u00f6rter ein:",instructions_context:"",instructions_audio:"Gib die 8 Ziffern ein:",help_btn:"Hilfe",incorrect_try_again:"Falsch. Nochmals versuchen!"},RecaptchaStr_es={visual_challenge:"Obt\u00e9n un reto visual",audio_challenge:"Obt\u00e9n un reto audible",refresh_btn:"Obt\u00e9n un nuevo reto",instructions_visual:"Escribe las 2 palabras:",instructions_context:"",instructions_audio:"Escribe los 8 n\u00fameros:",help_btn:"Ayuda",
incorrect_try_again:"Incorrecto. Otro intento."},RecaptchaStr_fr={visual_challenge:"D\u00e9fi visuel",audio_challenge:"D\u00e9fi audio",refresh_btn:"Nouveau d\u00e9fi",instructions_visual:"Entrez les deux mots:",instructions_context:"",instructions_audio:"Entrez les huit chiffres:",help_btn:"Aide",incorrect_try_again:"Incorrect."},RecaptchaStr_nl={visual_challenge:"Test me via een afbeelding",audio_challenge:"Test me via een geluidsfragment",refresh_btn:"Nieuwe uitdaging",instructions_visual:"Typ de twee woorden:",
instructions_context:"",instructions_audio:"Typ de acht cijfers:",help_btn:"Help",incorrect_try_again:"Foute invoer."},RecaptchaStr_pt={visual_challenge:"Obter um desafio visual",audio_challenge:"Obter um desafio sonoro",refresh_btn:"Obter um novo desafio",instructions_visual:"Escreva as 2 palavras:",instructions_context:"",instructions_audio:"Escreva os 8 numeros:",help_btn:"Ajuda",incorrect_try_again:"Incorrecto. Tenta outra vez."},RecaptchaStr_ru={visual_challenge:"\u0417\u0430\u0433\u0440\u0443\u0437\u0438\u0442\u044c \u0432\u0438\u0437\u0443\u0430\u043b\u044c\u043d\u0443\u044e \u0437\u0430\u0434\u0430\u0447\u0443",
audio_challenge:"\u0417\u0430\u0433\u0440\u0443\u0437\u0438\u0442\u044c \u0437\u0432\u0443\u043a\u043e\u0432\u0443\u044e \u0437\u0430\u0434\u0430\u0447\u0443",refresh_btn:"\u0417\u0430\u0433\u0440\u0443\u0437\u0438\u0442\u044c \u043d\u043e\u0432\u0443\u044e \u0437\u0430\u0434\u0430\u0447\u0443",instructions_visual:"\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0434\u0432\u0430 \u0441\u043b\u043e\u0432\u0430:",instructions_context:"",instructions_audio:"\u0412\u0432\u0435\u0434\u0438\u0442\u0435 \u0432\u043e\u0441\u0435\u043c\u044c \u0447\u0438\u0441\u0435\u043b:",
help_btn:"\u041f\u043e\u043c\u043e\u0449\u044c",incorrect_try_again:"\u041d\u0435\u043f\u0440\u0430\u0432\u0438\u043b\u044c\u043d\u043e."},RecaptchaStr_tr={visual_challenge:"G\u00f6rsel deneme",audio_challenge:"\u0130\u015fitsel deneme",refresh_btn:"Yeni deneme",instructions_visual:"\u0130ki kelimeyi yaz\u0131n:",instructions_context:"",instructions_audio:"Sekiz numaray\u0131 yaz\u0131n:",help_btn:"Yard\u0131m (\u0130ngilizce)",incorrect_try_again:"Yanl\u0131\u015f. Bir daha deneyin."},RecaptchaStr_it=
{visual_challenge:"Modalit\u00e0 visiva",audio_challenge:"Modalit\u00e0 auditiva",refresh_btn:"Chiedi due nuove parole",instructions_visual:"Scrivi le due parole:",instructions_context:"",instructions_audio:"Trascrivi ci\u00f2 che senti:",help_btn:"Aiuto",incorrect_try_again:"Scorretto. Riprova."},RecaptchaLangMap={en:RecaptchaStr_en,de:RecaptchaStr_de,es:RecaptchaStr_es,fr:RecaptchaStr_fr,nl:RecaptchaStr_nl,pt:RecaptchaStr_pt,ru:RecaptchaStr_ru,tr:RecaptchaStr_tr,it:RecaptchaStr_it};var RecaptchaStr=RecaptchaStr_en,RecaptchaOptions,RecaptchaDefaultOptions={tabindex:0,theme:"red",callback:null,lang:null,custom_theme_widget:null,custom_translations:null,includeContext:!1},Recaptcha={widget:null,timer_id:-1,style_set:!1,theme:null,type:"image",ajax_verify_cb:null,$:function(a){return typeof a=="string"?document.getElementById(a):a},create:function(a,b,c){Recaptcha.destroy();if(b)Recaptcha.widget=Recaptcha.$(b);Recaptcha._init_options(c);Recaptcha._call_challenge(a)},destroy:function(){var a=
Recaptcha.$("recaptcha_challenge_field");a&&a.parentNode.removeChild(a);Recaptcha.timer_id!=-1&&clearInterval(Recaptcha.timer_id);Recaptcha.timer_id=-1;if(a=Recaptcha.$("recaptcha_image"))a.innerHTML="";if(Recaptcha.widget)Recaptcha.theme!="custom"?Recaptcha.widget.innerHTML="":Recaptcha.widget.style.display="none",Recaptcha.widget=null},focus_response_field:function(){var a=Recaptcha.$,a=a("recaptcha_response_field");a.focus()},get_challenge:function(){if(typeof RecaptchaState=="undefined")return null;
return RecaptchaState.challenge},get_response:function(){var a=Recaptcha.$,a=a("recaptcha_response_field");if(!a)return null;return a.value},ajax_verify:function(a){Recaptcha.ajax_verify_cb=a;a=Recaptcha._get_api_server()+"/ajaxverify?c="+encodeURIComponent(Recaptcha.get_challenge())+"&response="+encodeURIComponent(Recaptcha.get_response());Recaptcha._add_script(a)},_ajax_verify_callback:function(a){Recaptcha.ajax_verify_cb(a)},_get_api_server:function(){var a=window.location.protocol,b;b=typeof _RecaptchaOverrideApiServer!=
"undefined"?_RecaptchaOverrideApiServer:"www.google.com/recaptcha/api";return a+"//"+b},_call_challenge:function(a){a=Recaptcha._get_api_server()+"/challenge?k="+a+"&ajax=1&cachestop="+Math.random();RecaptchaOptions.lang&&(a+="&lang="+RecaptchaOptions.lang);typeof RecaptchaOptions.extra_challenge_params!="undefined"&&(a+="&"+RecaptchaOptions.extra_challenge_params);RecaptchaOptions.includeContext&&(a+="&includeContext=1");Recaptcha._add_script(a)},_add_script:function(a){var b=document.createElement("script");
b.type="text/javascript";b.src=a;Recaptcha._get_script_area().appendChild(b)},_get_script_area:function(){var a=document.getElementsByTagName("head");return a=!a||a.length<1?document.body:a[0]},_hash_merge:function(a){var b={},c;for(c in a)for(var d in a[c])b[d]=a[c][d];b.theme=="context"&&(b.includeContext=!0);return b},_init_options:function(a){RecaptchaOptions=Recaptcha._hash_merge([RecaptchaDefaultOptions,a||{}])},challenge_callback:function(){var a=Recaptcha.widget;Recaptcha._reset_timer();RecaptchaStr=
Recaptcha._hash_merge([RecaptchaStr_en,RecaptchaLangMap[RecaptchaOptions.lang]||{},RecaptchaOptions.custom_translations||{}]);window.addEventListener&&window.addEventListener("unload",function(a){Recaptcha.destroy()},!1);Recaptcha._is_ie()&&window.attachEvent&&window.attachEvent("onbeforeunload",function(){});if(navigator.userAgent.indexOf("KHTML")>0){a=document.createElement("iframe");a.src="about:blank";a.style.height="0px";a.style.width="0px";a.style.visibility="hidden";a.style.border="none";var b=
document.createTextNode("This frame prevents back/forward cache problems in Safari.");a.appendChild(b);document.body.appendChild(a)}Recaptcha._finish_widget()},_add_css:function(a){var b=document.createElement("style");b.type="text/css";b.styleSheet?navigator.appVersion.indexOf("MSIE 5")!=-1?document.write("<style type='text/css'>"+a+"</style>"):b.styleSheet.cssText=a:navigator.appVersion.indexOf("MSIE 5")!=-1?document.write("<style type='text/css'>"+a+"</style>"):(a=document.createTextNode(a),b.appendChild(a));
Recaptcha._get_script_area().appendChild(b)},_set_style:function(a){if(!Recaptcha.style_set)Recaptcha.style_set=!0,Recaptcha._add_css(a+"\n\n.recaptcha_is_showing_audio .recaptcha_only_if_image,.recaptcha_isnot_showing_audio .recaptcha_only_if_audio,.recaptcha_had_incorrect_sol .recaptcha_only_if_no_incorrect_sol,.recaptcha_nothad_incorrect_sol .recaptcha_only_if_incorrect_sol{display:none !important}")},_init_builtin_theme:function(){var a=Recaptcha.$,b=RecaptchaStr,c=RecaptchaState,d,e,c=c.server;
c[c.length-1]=="/"&&(c=c.substring(0,c.length-1));var f=c+"/img/"+Recaptcha.theme;Recaptcha.theme=="clean"?(c=RecaptchaTemplates.CleanCss,d=RecaptchaTemplates.CleanHtml,e="png"):(Recaptcha.theme=="context"?(c=RecaptchaTemplates.VertCss,d=RecaptchaTemplates.ContextHtml):(c=RecaptchaTemplates.VertCss,d=RecaptchaTemplates.VertHtml),e="gif");c=c.replace(/IMGROOT/g,f);Recaptcha._set_style(c);Recaptcha.widget.innerHTML="<div id='recaptcha_area'>"+d+"</div>";a("recaptcha_reload").src=f+"/refresh."+e;a("recaptcha_switch_audio").src=
f+"/audio."+e;a("recaptcha_switch_img").src=f+"/text."+e;a("recaptcha_whatsthis").src=f+"/help."+e;if(Recaptcha.theme=="clean")a("recaptcha_logo").src=f+"/logo."+e,a("recaptcha_tagline").src=f+"/tagline."+e;a("recaptcha_reload").alt=b.refresh_btn;a("recaptcha_switch_audio").alt=b.audio_challenge;a("recaptcha_switch_img").alt=b.visual_challenge;a("recaptcha_whatsthis").alt=b.help_btn;a("recaptcha_reload_btn").href="javascript:Recaptcha.reload ();";a("recaptcha_reload_btn").title=b.refresh_btn;a("recaptcha_switch_audio_btn").href=
"javascript:Recaptcha.switch_type('audio');";a("recaptcha_switch_audio_btn").title=b.audio_challenge;a("recaptcha_switch_img_btn").href="javascript:Recaptcha.switch_type('image');";a("recaptcha_switch_img_btn").title=b.visual_challenge;a("recaptcha_whatsthis_btn").href=Recaptcha._get_help_link();a("recaptcha_whatsthis_btn").target="_blank";a("recaptcha_whatsthis_btn").title=b.help_btn;a("recaptcha_whatsthis_btn").onclick=function(){Recaptcha.showhelp();return!1};a("recaptcha_table").className="recaptchatable recaptcha_theme_"+
Recaptcha.theme;a("recaptcha_instructions_image")&&a("recaptcha_instructions_image").appendChild(document.createTextNode(b.instructions_visual));a("recaptcha_instructions_context")&&a("recaptcha_instructions_context").appendChild(document.createTextNode(b.instructions_context));a("recaptcha_instructions_audio")&&a("recaptcha_instructions_audio").appendChild(document.createTextNode(b.instructions_audio));a("recaptcha_instructions_error")&&a("recaptcha_instructions_error").appendChild(document.createTextNode(b.incorrect_try_again))},
_finish_widget:function(){var a=Recaptcha.$,b=RecaptchaStr,b=RecaptchaState,c=RecaptchaOptions,d=c.theme;switch(d){case "red":case "white":case "blackglass":case "clean":case "custom":case "context":break;default:d="red"}if(!Recaptcha.theme)Recaptcha.theme=d;Recaptcha.theme!="custom"?Recaptcha._init_builtin_theme():Recaptcha._set_style("");d=document.createElement("span");d.id="recaptcha_challenge_field_holder";d.style.display="none";a("recaptcha_response_field").parentNode.insertBefore(d,a("recaptcha_response_field"));
a("recaptcha_response_field").setAttribute("autocomplete","off");a("recaptcha_image").style.width="300px";a("recaptcha_image").style.height="57px";Recaptcha.should_focus=!1;Recaptcha._set_challenge(b.challenge,"image");if(c.tabindex&&(a("recaptcha_response_field").tabIndex=c.tabindex,Recaptcha.theme!="custom"))a("recaptcha_whatsthis_btn").tabIndex=c.tabindex,a("recaptcha_switch_img_btn").tabIndex=c.tabindex,a("recaptcha_switch_audio_btn").tabIndex=c.tabindex,a("recaptcha_reload_btn").tabIndex=c.tabindex;
if(Recaptcha.widget)Recaptcha.widget.style.display="";c.callback&&c.callback()},switch_type:function(a){var b=Recaptcha;b.type=a;b.reload(b.type=="audio"?"a":"v")},reload:function(a){var b=Recaptcha,c=b.$,c=RecaptchaState;typeof a=="undefined"&&(a="r");c=c.server+"reload?c="+c.challenge+"&k="+c.site+"&reason="+a+"&type="+b.type;RecaptchaOptions.lang&&(c+="&lang="+RecaptchaOptions.lang);RecaptchaOptions.includeContext&&(c+="&includeContext=1");typeof RecaptchaOptions.extra_challenge_params!="undefined"&&
(c+="&"+RecaptchaOptions.extra_challenge_params);b.type=="audio"&&(c+=RecaptchaOptions.audio_beta_12_08?"&audio_beta_12_08=1":"&new_audio_default=1");b.should_focus=a!="t";b._add_script(c)},finish_reload:function(a,b){RecaptchaState.is_incorrect=!1;Recaptcha._set_challenge(a,b)},_set_challenge:function(a,b){var c=Recaptcha,d=RecaptchaState,e=c.$;d.challenge=a;c.type=b;e("recaptcha_challenge_field_holder").innerHTML="<input type='hidden' name='recaptcha_challenge_field' id='recaptcha_challenge_field' value='"+
d.challenge+"'/>";if(b=="audio")e("recaptcha_image").innerHTML=Recaptcha.getAudioCaptchaHtml();else if(b=="image"){var f=d.server+"image?c="+d.challenge;e("recaptcha_image").innerHTML="<img style='display:block;' height='57' width='300' src='"+f+"'/>"}Recaptcha._css_toggle("recaptcha_had_incorrect_sol","recaptcha_nothad_incorrect_sol",d.is_incorrect);Recaptcha._css_toggle("recaptcha_is_showing_audio","recaptcha_isnot_showing_audio",b=="audio");c._clear_input();c.should_focus&&c.focus_response_field();
c._reset_timer()},_reset_timer:function(){var a=RecaptchaState;clearInterval(Recaptcha.timer_id);Recaptcha.timer_id=setInterval("Recaptcha.reload('t');",(a.timeout-300)*1E3)},showhelp:function(){window.open(Recaptcha._get_help_link(),"recaptcha_popup","width=460,height=580,location=no,menubar=no,status=no,toolbar=no,scrollbars=yes,resizable=yes")},_clear_input:function(){var a=Recaptcha.$("recaptcha_response_field");a.value=""},_displayerror:function(a){var b=Recaptcha.$;b("recaptcha_image").innerHTML=
"";b("recaptcha_image").appendChild(document.createTextNode(a))},reloaderror:function(a){Recaptcha._displayerror(a)},_is_ie:function(){return navigator.userAgent.indexOf("MSIE")>0&&!window.opera},_css_toggle:function(a,b,c){var d=Recaptcha.widget;if(!d)d=document.body;var e=d.className,e=e.replace(RegExp("(^|\\s+)"+a+"(\\s+|$)")," "),e=e.replace(RegExp("(^|\\s+)"+b+"(\\s+|$)")," ");e+=" "+(c?a:b);d.className=e},_get_help_link:function(){var a=RecaptchaState,a="http://www.google.com/recaptcha/help?c="+
a.challenge;RecaptchaOptions.lang&&(a+="&lang="+RecaptchaOptions.lang);return a},playAgain:function(){var a=Recaptcha.$;a("recaptcha_image").innerHTML=Recaptcha.getAudioCaptchaHtml()},getAudioCaptchaHtml:function(){var a=Recaptcha,b=RecaptchaState,c=Recaptcha.$,c=b.server+"image?c="+b.challenge;c.indexOf("https://")==0&&(c="http://"+c.substring(8));b=b.server+"/img/audiocaptcha.swf?v2";a=a._is_ie()?'<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="audiocaptcha" width="0" height="0" codebase="https://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab"><param name="movie" value="'+
b+'" /><param name="quality" value="high" /><param name="bgcolor" value="#869ca7" /><param name="allowScriptAccess" value="always" /></object><br/>':'<embed src="'+b+'" quality="high" bgcolor="#869ca7" width="0" height="0" name="audiocaptcha" align="middle" play="true" loop="false" quality="high" allowScriptAccess="always" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer"></embed> ';c=(Recaptcha.checkFlashVer()?'<br/><a class="recaptcha_audio_cant_hear_link" href="#" onclick="Recaptcha.playAgain(); return false;">'+
RecaptchaStr.play_again+"</a>":"")+'<br/><a class="recaptcha_audio_cant_hear_link" target="_blank" href="'+c+'">'+RecaptchaStr.cant_hear_this+"</a>";return a+c},gethttpwavurl:function(){var a=RecaptchaState;if(Recaptcha.type=="audio")return a=a.server+"image?c="+a.challenge,a.indexOf("https://")==0&&(a="http://"+a.substring(8)),a;return""},checkFlashVer:function(){var a=navigator.appVersion.indexOf("MSIE")!=-1?!0:!1,b=navigator.appVersion.toLowerCase().indexOf("win")!=-1?!0:!1,c=navigator.userAgent.indexOf("Opera")!=
-1?!0:!1,d=-1;if(navigator.plugins!=null&&navigator.plugins.length>0){if(navigator.plugins["Shockwave Flash 2.0"]||navigator.plugins["Shockwave Flash"])a=navigator.plugins["Shockwave Flash 2.0"]?" 2.0":"",a=navigator.plugins["Shockwave Flash"+a].description,a=a.split(" "),a=a[2].split("."),d=a[0]}else if(a&&b&&!c)try{var e=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7"),f=e.GetVariable("$version"),d=f.split(" ")[1].split(",")[0]}catch(g){}return d>=9},getlang:function(){return RecaptchaOptions.lang}};

